Eslam Totti
Eslam Totti

Reputation: 125

Regex in C# , Expression in negative lookbehind

I`m trying to write an expression to match a single quote preceded by an odd number of question marks.

I have found a negative look-behind expression to match a single question mark

pattern (?<!\?)'

aaa?'aaa   match
aaa'aaaa   not match
aaa??'aaa  match --wrong

But what I need is to detect an odd number of question marks, not just one.
I tried to put it like (?<!\?(??))' but it did not work.

The result I want is

aaa?'aaaa  match
aaa??'aaaa  not match
aaa???'aaaa  match
aaa????'aaaa  not match
aaa?????'aaaa  match

Upvotes: 1

Views: 655

Answers (2)

Jon
Jon

Reputation: 437336

The regex you are looking for is (?<=(^|[^?])(\?\?)*\?)'.

Let's break the lookbehind (I changed it to positive) down:

(^|[^?]) not a question mark (possibly also start of string, i.e. nothing)
(\?\?)*  any number of question mark pairs
\?       a single question mark

So in order for the quote to match, it has to be preceded by these tokens in reverse order. It should be clear that this forces the number of preceding question marks to be exactly 2N + 1 for some N >= 0.

Upvotes: 3

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

I don't think you need to use any lookaround for this matching. Try this one:

([^\?]|^)\?(\?\?)*([^\?]|$)

It is checking whether the ? sign is in between the non question mark sign or at the end of start of the string.

Though I am not sure what will happen for the input like aaa?????'aaaa??

Upvotes: 3

Related Questions