views:

57

answers:

2

I want to check whether there is string starting from number and then optional character with the help of the regex.So what should be the regex for matching the string which must be started with number and then character might be there or not.Like there is string "30a" or "30" it should be matched.But if there is "a" or some else character or sereis of characters, string should not be matched.

A: 
^\d.*

The ^ matches the start of the string, \d matches a single digit, and then the .* matches any number of additional characters.

Thus, the net result is that it will only match if the string begins with a digit.

Amber
@Dav,hi when I store the regex in the string variable it gives error like Unrecognize escape sequence.
Harikrishna
Be sure to turn off escaping in c#, like this `Regex.Match(@"\d+\w*", instr)`. Notice the `@` before the regex string.
Jason Webb
@BigJason,thanks,but the why we use @ to turn off escaping, what is escaping ?
Harikrishna
Normally a backslash followed by another character in a string literal is an "escape sequence" - they're used in place of characters that couldn't normally be typed in a string, such as a newline (`\n`). Since you actually want to pass `\d` as the literal characters for the regex, you turn off escaping; otherwise you'd have to manually escape the backslash character to ` \\ `
Amber
Character escaping is a way to represent (usually) non human readable characters in a string. So "Line1\nLine2" actually puts a carriage return in the middle of the string because `\n` is the character escape for new line. In c# putting an `@` before the string tells the compiler to ignore those character escapes.
Jason Webb
Thanks to BigJason And Dav.
Harikrishna
@Dav,Sorry but your regex does not work for 46.
Harikrishna
@Harikrishna: er, what? There's no reason it shouldn't.
Amber
+2  A: 

Sounds like there should be able to be any number of numeric characters at the beginning followed by optional other characters. To match any other character after a series of numbers at the beginning I would use:

\d+.*

To match only alpha numeric characters after the mandatory numeric beginning I would use:

\d+\w*

Note: as pointed out by Dav, if you add a ^ to the start of the expression and a $ to the end of the expression like this ^\d+\w*$ you will ensure the whole string matches. However if you leave those off, you will be able to search the input string for what you need. It just depends on what your needs are.

Jason Webb