3

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/

gyula
  • 229
  • 3
  • 7
  • 12
  • 2
    You have `findall`, it is `g`. `i` can be added as `re.I` in `pattern = re.compile(search_pattern, re.I)`. `search_pattern = r"/somestring/gi"` -> `search_pattern = r"somestring"`. You can actually get the code from the [*code generator* section at regex101.com](https://regex101.com/r/nS4xV3/1). – Wiktor Stribiżew Aug 10 '15 at 09:52
  • 1
    Now we get questions about how to use regex101. I believe such question should not be here. – nhahtdh Aug 10 '15 at 11:02

3 Answers3

4

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

When I started using python, I also wondered the same. But unfortunately, python does not provide special delimiters for creating regex. At the end of day, regex are just string. So, you cannot specify modifiers along with string unlike javascript or ruby.

Instead you need to compile the regex with modifiers.

regex = re.compile(r'something', re.IGNORECASE | re.DOTALL)
queries = regex.findall(content)
hspandher
  • 15,934
  • 2
  • 32
  • 45
0
search_pattern =  r"somestring"
pattern = re.compile(search_pattern,flags=re.I)
                                          ^^^   
print pattern.findall("somestriNg")

You can set flags this way.findall is global by default.Also you dont need delimiters in python.

vks
  • 67,027
  • 10
  • 91
  • 124