wyc
wyc

Reputation: 55293

Don't match if there's a "period" between "word" and "?"

Perhaps he hadn't. [Perhaps he didn't?]

Perhaps he didn't.

[Perhaps he hadn't?]

I want to match the bits in brackets; sentences that start with "Perhaps" and end with a question mark.

I thought this regex would work: Perhaps.*(?!=\.)\?

However, what I'm getting is this:

[Perhaps he hadn't. Perhaps he didn't?]

Perhaps he didn't.

[Perhaps he hadn't?]

Why is this? And how to fix it?

https://regexr.com/5dfhs

Upvotes: 1

Views: 47

Answers (1)

anubhava
anubhava

Reputation: 785671

You may use a negated character class like this:

/Perhaps[^.?]*\?/g

RegEx Demo

To match complete word use:

/\bPerhaps[^.?]*\?/

And to avoid matching across lines use:

/\bPerhaps[^.?\r\n]*\?/

here [^.?] would match any character except . and ?

About your regex:

(?!=\.) is actually wrong syntax for a negative lookahead. It just means don't match if we have a literal = and . ahead.

Even if you correct it to use Perhaps.*(?!\.)\? it will still not work because (?!\.) will only be applied for matching ? and that will always succeed.

Though not recommended but if you really want to use a negative lookahead then use:

/Perhaps(?:(?!\.).)*\?/

Upvotes: 2

Related Questions