user517406
user517406

Reputation: 13773

Regex after character

I am trying to use a regex to get the value after a character. In this case, the string is m325 and I need to get whatever is after the m.

Can anybody tell me what is wrong with my code?

Regex rgMeter = new Regex("m(.+$");
intMeterID = Convert.ToInt32(rgMeter.Match(strID));

Update:

Thanks for all your answers...for some reason the regex "m(.+)$" is returning the m as well as the string I require. I have tried the Groups example and it returns the data that I want. Why do I need to use Groups to do this?

Upvotes: 5

Views: 5179

Answers (7)

macarthy
macarthy

Reputation: 3069

The regex you require is /^m(.*)$/

Actually you should use \d or [0-9] if you want match digits.

/^m([0-9]*)$/ 

and

/^m([0-9]{3})$/

if there are always 3 digits

Upvotes: 1

Mormegil
Mormegil

Reputation: 8071

Apart from the missing ), you oversimplified it a bit. You need to do

Regex rgMeter = new Regex("m(.+)$");
intMeterID = Convert.ToInt32(rgMeter.Match(strID).Groups[1].Value);

(Possibly, you might want to add a check if the Match() matched or not.)

Upvotes: 5

user482954
user482954

Reputation:

Also, you can test it on: http://gskinner.com/RegExr/

What values can appear behind the "m" character? If it's only an integer, the I should use the solution Shekhar_Pro provided.. If any character, go with the rest :)

Upvotes: 1

mmix
mmix

Reputation: 6278

You are missing a closing ). Plus, if you are extracting a number you should limit yourself to digits only, Will avoid trying to parse a faulty string into integer in the next statement.

m(\d*)

Upvotes: 2

Shekhar_Pro
Shekhar_Pro

Reputation: 18420

A simple "m\d*" should do this.. please show us whole string to see the case.

Upvotes: 0

SergeS
SergeS

Reputation: 11779

"m(.+)$" - there wasn't closed (

Upvotes: 1

MSalters
MSalters

Reputation: 179779

Looks like you missed the closing )

Upvotes: 0

Related Questions