May I know what \? means in a regular expression? For example, what is its significance in this expression.
I have used this for validating 7 digit telephone no
Any help is highly appreciated.
"\?" means "?" itself. "\" - is escape character. "?" is quantifier and "\" is used to escape it.
I have used this for validating 7 digit telephone no
"[[:number:]]\{3\}[ -]\?[[:number:]]\{4\}"
Looking at your example, it seems that you are talking about BRE, then the \ (escaping) gave ? special meaning: one or zero[ -]
If it is ERE/PCRE, the \ will take that speical meaning away from ?, that is, \? means literal question mark: ?
The properly-escaped "?" will match that exact character, the "?", as it appears in the text.
For instance, if you do
Regex re = new Regex(#"\d{3}-\?\d{4}");
, you will be able to get a positive match for 123-?1234.
If you want to get a positive match for 1231234 OR 123-1234, you can use the special character "?" without escape, like this:
Regex re = new Regex(#"\d{3}-?\d{4}");
P.S. for C# .NET, I find the best regex-testing place online is MyRegexTester. If you use it for C#, don't forget to check the appropriate "C# .NET" checkbox.
P.P.S. as per the comment, putting "\s*" into the regex will match any length white space (spaces and tabs included), "\ ?" will match an optional space, and "[ ]" will match exactly one space (no less).
"\?" escapes "?" that have a special meaning in the regex (0 or 1 match) so "\?" escapes it and identifies the literal "?"
your regex looks strange to me, it looks that all the special character are escaped (also "{" ) and doesn't appear to be valid from what i know.
i think you want to write
"\d{3}[ -]?\d{4}"
if you want to match something that respect the pattern or
"^\d{3}[ -]?\d{4}$"
if you want to have a match something that is exactly the pattern
Related
My Regex is for a canadian postal code and only allowing the valid letters:
Regex pattern = new Regex("^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][/s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$");
The problem I am having is that I want to allow for a space to be put in between the each set but cannot find the correct character to use.
You've got a forward-slash instead of a backslash in your regular expression for whitespace (\s). The following regex should work.
#"^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][\s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$"
If you are simply searching for space use \s
To provide the escape sequence character \ use # verbitm literal character as below in the given example.
Regex pattern = new Regex(#"^[ABCEGHJKLMNPRSTVXY][0-9]\s[ABCEGHJKLMNPRSTVWXYZ[0-9]\s[ABCEGHJKLMNPRSTVWXYZ][0-9]$");
As pointed out in the comments, if space is optional you can use ? quantifier as below.
Regex pattern = new Regex(#"^[ABCEGHJKLMNPRSTVXY][0-9]\s?[ABCEGHJKLMNPRSTVWXYZ[0-9]\s?[ABCEGHJKLMNPRSTVWXYZ][0-9]$");
Use the \s token for whitespace instead of /s.
Some handy tools to speed up regex development:
regexr.com helps with syntax and provides realtime testing
regexpr.com (yes I know :)) visualizes your expression.
As per other answers....
Use \s instead of /s
You shouldn't need to square bracket the [\s], because it already implies a complete class of characters.
Also...
In most languages, you probably don't want to use double quotes "..." as delimiters to the Regex, since this might be interpolating the \s before the pattern is applied. It's certainly worth a try.
Use a trailing quantifier \s* or \s? to allow the space to be optional.
What I am trying to do is fairly simple, although I am running into difficulty. I have a string that is a url, it will have the format http://www.somedomain.com?id=someid what I want to retrive is the someid part. I figure I can use a regular expression but I'm not very good with them, this is what I tried:
Match match = Regex.Match(theString, #"*.?id=(/d.)");
I get a regex exception saying there was an error parsing the regex. The way I am reading this is "any number of characters" then the literal "?id=" followed "by any number of digits". I put the digits in a group so I could pull them out. I'm not sure what is wrong with this. If anyone could tell me what I'm doing wrong I would appreciated it, thanks!
No need for Regex. Just use built-in utilities.
string query = new Uri("http://www.somedomain.com?id=someid").Query;
var dict = HttpUtility.ParseQueryString(query);
var value = dict["id"]
You've got a couple of errors in your regex. Try this:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
Specifically, I:
changed *. to .* (dot matches all non-newline chars and * means zero or more of the preceding)
added a an escape sequence before the ? because the question mark is a special charcter in regular expressions. It means zero or one of the preceding.
changed /d. to \d* (you had the slash going the wrong way and you used dot, which was explained above, instead of * which was also explained above)
Try
var match = RegEx.Match(theString, #".*\?id=(\d+)");
The error is probably due to preceding *. The * character in regex matches zero or more occurrences of previous character; so it cannot be the first character.
Probably a typo, but shortcut for digit is \d, not /d
. matches any character, you need to match one or more digits - so use a +
? is a special character, so it needs to be escaped.
So it becomes:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
That being said, regex is not the best tool for this; use a proper query string parser or things will eventually become difficult to manage.
I am trying to capture a value out of a string. The string's format should be
01+XXXX
and I want to capture XXXX using a regular expression. This is what I came up with -
01+\\s*(?<1>[.0-9]*)
But that won't work. What DOES work is -
01+\\s*(?<1>[+.0-9]*)
The only difference is adding the + into the character class. My main question is - why does the second expression work and the first expression doesn't? In the first one, I look for 01+ and the rest of it should go to [.0-9]. It seems to me that the second one wants to read + twice - is that not what its doing? I am pretty new to regular expressions so I feel like I might be missing something small.
On this site http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial it says that + is used for "Repeat one or more times". So is it trying to read 01+ more than once?
It's reading the 1 one or more times. That is, the regex 01+ matches 01 or 011 or 0111 etc.
But it doesn't match the +. If you want to match a literal +, write 01\+ or 01[+] for the regex.
The + is a special character, meaning "one or more times." In this case, it means 01, 011, 0111, etc. instead of 01+. If you want to use it literally, you need to escape it, like this: \+
Note: It looks like you are using it with strings, so you would need to double-escape: \\+
It works inside a character class ([+]) because character classes take most characters literally, with exceptions including \ and ].
'+' is a special character in regex, it means "1 or more times". So what you have written means:
The character '0'
The character '1' one or more times
Whitespace 0 or more times
etc.
If you want to match a literal plus you need to escape it:
01\+\\s*(?<1>[.0-9]*)
The + is a quantifier, as explained in the tutorial you linked. So, your regex means "match a zero, then one or more ones, then zero or more whitespaces, then ...".
The plus needs to be escaped:
01\\+\\s*(?<1>[.0-9]*)
Your second regex worked, because the + there was part of a character class and does not need to be escaped there.
01\+(?<cap>[\d.]*)
explain:
01 '01'
\+ '+'
[\d.]* any character of: digits (0-9), '.'
(0 or more times, matching the most amount possible)
I'm currently facing a (little) blocking issue. I'd like to replace a substring by one another using regular expression. But here is the trick : I suck at regex.
Regex.Replace(contenu, "Request.ServerVariables("*"))",
"ServerVariables('test')");
Basically I'd like to replace whatever is between the " by "test". I tried ".{*}" as a pattern but it doesn't work.
Could you give me some tips, I'd appreciate it!
There are several issues you need to take care of.
You are using special characters in your regex (., parens, quotes) -- you need to escape these with a slash. And you need to escape the slashes with another slash as well because we 're in a C# string literal, unless you prefix the string with # in which case the escaping rules are different.
The expression to match "any number of whatever characters" is .*. In this case, you would want to match any number of non-quote characters, which is [^"]*.
In contrast to (1) above, the replacement string is not a regular expression so you don't want any slashes there.
You need to store the return value of the replace somewhere.
The end result is
var result = Regex.Replace(contenu,
#"Request\.ServerVariables\(""[^""]*""\)",
"Request.ServerVariables('test')");
Based purely on my knowledge of regex (and not how they are done in C#), the pattern you want is probably:
"[^"]*"
ie - match a " then match everything that's not a " then match another "
You may need to escape the double-quotes to make your regex-parser actually match on them... that's what I don't know about C#
Try to avoid where you can the '.*' in regex, you can usually find what you want to get by avoiding other characters, for example [^"]+ not quoted, or ([^)]+) not in parenthesis. So you may just want "([^"]+)" which should give you the whole thing in [0], then in [1] you'll find 'test'.
You could also just replace '"' with '' I think.
Taryn Easts regex includes the *. You should remove it, if it is just a placeholder for any value:
"[^"]"
BTW: You can test this regex with this cool editor: http://rubular.com/r/1MMtJNF3kM
What is the regular exp for a text that can't contain any special characters except space?
Because Prajeesh only wants to match spaces, \s will not suffice as it matches all whitespace characters including line breaks and tabs.
A character set that should universally work across all RegEx parsers is:
[a-zA-Z0-9 ]
Further control depends on your needs. Word boundaries, multi-line support, etc... I would recommend visiting Regex Library which also has some links to various tutorials on how Regular Expression Parsing works.
[\w\s]*
\w will match [A-Za-z0-9_] and the \s will match whitespaces.
[\w ]* should match what you want.
Assuming "special characters" means anything that's not a letter or digit, and "space" means the space character (ASCII 32):
^[A-Za-z0-9 ]+$
You need #"^[A-Za-z0-9 ]+$". The \s character class matches things other than space (such as tab) and you since you want to match sure that no part of the string has other characters you should anchor it with ^ and $.
If you just want alphabets and spaces then you can use: #"[A-Za-z\s]+" to match at least one character or space. You could also use #"[A-Za-z ]+" instead without explicitly denoting the space.
Otherwise please clarify.
In C#, I'd believe it's ^(\w|\s)*$