Sorry I'm not a English native speaker.
Introduction
I'm a noob in regex.
I'm searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
I've looked around and apparently I've got the choice between these solutions:
A(?!B)
, A(?=B)
, (?<=B)A
, (?<!B)A
. I even permuted and combined them in different ways, but seems no use.
Question
I want my regex to match independent A but not B, (A ⊆ B).
For example,
(Spaces are to read it more clearly, spaces are not include in strings below)
Let A=
123
, B=12345
, matching result (bold): '1345 12345 2345 1234 1235'Let A=
in
, B=hint|find
, matching result (bold): "She finds a hint in the king's pocket."
How should I build the regex?
CodePudding user response:
If the regex engine you're using supports a capture group (any regex engine that supports lookaround assertions should), you can use a negative lookahead pattern to exclude B
, and assert that the match starts with a word boundary and are zero to many word characters leading to A
, and capture A
in a capture group for output.
Using your second input as an example:
(?!hint|find)\b\w*(in)
Demo: https://regex101.com/r/sV59fQ/1
EDIT: Since you've added a test case of Shefindsahintintheking'spocket
in the comment below, a word boundary assertion wouldn't be useful here.
Instead, you can simply match B|(A)
so that matches of B
consumes the chance of matching A
, but output only when what's captured by the capture group is not empty.
Using your second input as an example again:
hint|find|(in)