Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add modifers to regex in python?

Tags:

python

regex

I want to add these two modifiers: g - global , i - insensitive

here is a par of my script:

search_pattern =  r"/somestring/gi"
pattern = re.compile(search_pattern)

queries = pattern.findall(content)

but It does not work the modifiers are as per on this page https://regex101.com/

like image 463
gyula Avatar asked Sep 02 '25 04:09

gyula


1 Answers

First of all, I suggest that you should study regex101.com capabilities by checking all of its resources and sections. You can always see Python (and PHP and JS) code when clicking code generator link on the left.

How to obtain g global search behavior?

The findall in Python will get you matched texts in case you have no capturing groups. So, for r"somestring", findall is sufficient. In case you have capturing groups, but you need the whole match, you can use finditer and access the .group(0).

How to obtain case-insensitive behavior?

The i modifier can be used as re.I or re.IGNORECASE modifiers in pattern = re.compile(search_pattern, re.I). Also, you can use inline flags: pattern = re.compile("(?i)somestring").

A word on regex delimiters

Instead of search_pattern = r"/somestring/gi" you should use search_pattern = r"somestring". This is due to the fact that flags are passed as a separate argument, and all actions are implemented as separate re methods.

So, you can use

import re
p = re.compile(r'somestring', re.IGNORECASE)
test_str = "somestring"
re.findall(p, test_str)

Or

import re
p = re.compile(r'(?i)(some)string')
test_str = "somestring"
print([(x.group(0),x.group(1)) for x in p.finditer(test_str)])

See IDEONE demo

like image 134
Wiktor Stribiżew Avatar answered Sep 04 '25 18:09

Wiktor Stribiżew