How to ignore a specific word in lookbehind?

Viewed 176

Full string:

See Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.
**Here Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**

I'm using this code to get the sentence in **:

(?i)(?<=\D|![see])Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)

by giving the specific word See to ignore it.

But it's still taking both sentences.

4 Answers

Try

(?i)(?<=\D)(?<!See )Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)

It means to have something different of a digit before (?<=\D) but also refusing the "See " thing (?<!See ).

I'd recommend antoher pattern (?<=\*\*).+?(?=\*\*)

Explanation:

(?<=\*\*) - positive lookbehind: assert what preceds is **

.+? - match one or more characters (non-greedy)

(?=\*\*) - positive lookahead: assert what follows is **

Demo

If you want to add a quantifier )(?<!\bSee\b.*) in the lookbehind, you could use the PyPi regex module.

(?<=\D)(?<!\bSee\b.*)Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)

Python demo

Assuming the ** are there to indicate the difference between the sentences you can see the the second one is matched due to the ** at the end.

For example

import regex

pattern = r"(?i)(?<=\D)(?<!\bSee\b.*)Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)"
test_str = ("See Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.\n"
            "**Here Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**")
m = regex.search(pattern, test_str)
print(m.group())

Output

Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**

Another option could be to match what you don't want and capture what you want to keep using an alternation.

Match a whole line where See comes before Item, and capture in group 1 using the pattern with the lookbehind asserting not a digit.

(?:^(?:(?!\bItem\b.)*)See\b.*|((?<=\D)Item.+?1A.+?Risk Factors(?=\D).+?(?=Item 1B|$)))

Regex demo

you can use a negative lookbehind :

(?<!See ) 

will not match if "See " is before the sentence

Related