Junior Mayhe
Junior Mayhe

Reputation: 16411

Smallest pattern for extracting string value using RegEx

I'm trying to instantiate a Regex with the correct pattern for getting only the right value of a string. My text file has:

Comment ID : 1234.5

and I would like to get the right value as follows:

1234.5

What would be the correct Regex pattern?

here what I have so far

new Regex(@"^Comment ID\s*:\s*(?<comment_id>\w+)", RegexOptions.Multiline | RegexOptions.IgnoreCase); 

But this brings also the unneeded string "Comment ID"

Would be possible to not use the group marker <comment_id> ?

Upvotes: 1

Views: 342

Answers (4)

Loki Kriasus
Loki Kriasus

Reputation: 1301

You don't have to use group names - but then you will have to reference them by indexes. If left part of strings cannot contain ":" then the regex can be:

^[^:]+:\s*(.*?)\s*$

Also, you can use intance String.Split() method:

"abc : def".Split(new[] { ':' }, 2)

Upvotes: 1

arena-ru
arena-ru

Reputation: 1020

Regex you provided "^Comment ID\s*:\s*(?<comment_id>\w+)" doesn't match numbers after dot

Try to use this: (?!^Comment ID\s*:\s*)(?<comment_id>\d+\.*\d*)

Also you can change Comment ID to any words or \w+

Upvotes: 0

mbeckish
mbeckish

Reputation: 10579

(?<=Comment ID :\s*)[^\s]+

Upvotes: 0

thecoop
thecoop

Reputation: 46128

If you don't care whats left of the : you can just use:

"^.*:\s*(?<comment_id>\w+)"

You won't need to use the RegexOptions for this one, either, as there's no strings to ignore the case of

Upvotes: 0

Related Questions