John
John

Reputation: 285

C# Regex for multiple instances of pattern

I am trying to come up with a regular expression that will capture a string that contains two instances of "(v#)" (where # can be any number). For example, the string "Test (v6)" would not be captured, but "Test (v6) Word (v2)" would be since it contains two instances of the "(v#)". The furthest I've gotten is:

^.*?(\((v)(\d+)(\))){2}

but that only works if the version numbers ("(v#)") are right next to each other.

UPDATE:

Actually my issue would be solved if I could get the regular expression to make sure that the very end of the string contains (v#). I really want to ignore the middle version number. I know that involves using $ instead of ^ but that's all I have so far.

Upvotes: 0

Views: 108

Answers (3)

nickytonline
nickytonline

Reputation: 6981

If all you really care about is the version at the end, just do this:

\s+\((?<version>v\d+)\)$

And here's an explanation of what's going on.

Any whitespace character 
+ (one or more times)
(
Capture to <version>
  v
  Any digit 
  + (one or more times)
End Capture
)$ (anchor to end of string)

Upvotes: 1

femtoRgon
femtoRgon

Reputation: 33341

Extend your (outer) parentheses to include the .*?, so you have this:

^(.*?\((v)(\d+)(\))){2}

Also, don't know if you are using these capturing groups here (in which case feel free to ignore this) but might be easier to understand what's going one if you got rid of some extraneous parentheses:

^(.*?\(v\d+\)){2}

Upvotes: 0

Dave Sexton
Dave Sexton

Reputation: 11188

How about this:

^.*\(\s*v\d+\s*\).*\(\s*v\d+\s*\).*$

Upvotes: 0

Related Questions