Python Regex (finding multiple values ​​on a single line)

In python regex, how would I match a large string of text and flag if any of the regex values ​​match ... I tried this with "|" or statements, and I tried to create a list of regular expressions .. didn't work for me .. here is an example of what I'm trying to do with or ..

I think my "or" gets a comment

patterns=re.compile(r'[\btext String1\b] | [\bText String2\b]')   

if(patterns.search(MyTextFile)):
     print ("YAY one of your text patterns is in this file")

The above code always says that it matches regardless of whether the string appears, and if I change it a bit, I get matches in the first regular expression, but never checks the second .... I believe this is because "Raw "comments from mine or statement, but how would I get around this?

I also tried to work around this by pulling out the "Raw" instruction and putting double slashes on my \ b for escaping, but that didn't work either :(

patterns=re.compile(\\btext String1\\b | \\bText String2\\b)   

if(patterns.search(MyTextFile)):
     print ("YAY one of your text patterns is in this file")

Then I tried to make 2 separate source expressions using and / or an interpreter complaining about unsupported str operands of str ...

patterns=re.compile(r'\btext String1\b' | r'\bText String2\b')   

if(patterns.search(MyTextFile)):
     print ("YAY one of your text patterns is in this file")
+3
source share
3 answers
patterns=re.compile(r'(\btext String1\b)|(\bText String2\b)')   

You want a group (possibly capture), not a character class. Technically, you don't need a group here:

patterns=re.compile(r'\btext String1\b|\bText String2\b')   

will also work (without any capture).

As you had it, he checked either one of the characters between the first square brackets, or one of them between the second pair. You can find a regular expression tutorial .

, " str-". OR, | , compile.

+7

[\ btext String1\b] , " " "text String1". , - .

0

RE [ ] " " ( , , " " " , ", ^ [). , , , - , ; -).

0

Source: https://habr.com/ru/post/1755122/


All Articles