问题
I thought this would be a common and easy thing to do, but so far I've been unable to find an answer by Googling.
How would I regex match a substring only if it is not immediately preceded by a specific string?
In this case I want to match " (a space followed by a quotation mark) but only if it's not preceded by , (a comma). I've tried a few different things. Currently (?!,) " is as close as I've gotten, but the negative lookahead doesn't seem to be working as I expect.
Some examples of what I want:
Laura said "What have you done?" - 1 match
Laura said, "What have you done?" - 0 matches (there's a comma)
"Come with me," David said. - 0 matches (no space before the ")
Michael said "Throw it!" Jessica replied, "I'd rather not..." Shia shouted "Just do it!"
- 2 matches
This is in Notepad++. What am I doing wrong?
回答1:
This seemed to work for me, tested in Notepad++:
[^,]\K "
回答2:
You can use double assertions to apply two conditions.
(?<= )(?<!, )"
(?<= ) -> Positive lookbehind assertion which asserts that the character going to be matched must be preceded by a space character.
(?<!, ) -> Negative lookbehind which asserts that the character going to be matched must not be preceded by a ,<space> characters.
" -> match the double quotes only if both conditions gets satisfied.
OR
(?<=[^,] )"|(?<=^ )"
(?<=[^,] )" -> positive lookbehind which asserts that the double quotes must be preceeded by
- any char but not of ,
[^,] - followed by a space character
And note that this regex won't match a double quotes preceded by a space char exists at the line start like this *. In-order to match the quotes exists at the line start, we have to use another condition like
(?<=^ )" matches the quotes which was preceded by,
^start of the line.<space>character
On ORing these two conditions with | OR operator, you can achieve the expected results.
DEMO
If you want to match also the preceding space then remove the space from lookahead assertions.
(?<!,) "
(?<!,) asserts that the chars going to be matched won't be preceded by ,.
DEMO
来源:https://stackoverflow.com/questions/48071699/regex-match-a-substring-if-that-substring-is-not-preceded-by-a-specific-string