Question

when I am using a Regular Expression in .NET like

(.+) (c b|b)

and I have a string like "somestring c b" I am always getting "somestring c" in the first group and "b" in the second group.

I want to get "somestring" in the first group and "c b" in the the second group.

Any idea?

Was it helpful?

Solution

(.+?) (c b|b)

? is the lazy qualifier, which says to match the minimum number of characters required to satisfy the overall regex.

Here is a grid of them and more details

OTHER TIPS

A simple solution would be to make the first group reluctant by adding a question mark after the plus, like this:

(.+?) (c b|b)

Without that, it won't be greedy and match as many valid characters as it can, which in your case, means matching the c in that first group.

Put what you want to match inside the parentheses, and put the "or" symbol between your acceptable matches. For instance this RegEx should do the trick:

(.+ b|b)

Do it as below

(.+[^c]) (c b|b)

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top