-2

Need help in understanding the following examples.

>>> re.search('*.script', 'a.script')
Traceback (most recent call last):
<snipped>
re.error: nothing to repeat at position 0
>>> re.search('\*.script', 'a.script')
>>> re.search('a.script', 'a.script')
<re.Match object; span=(0, 8), match='a.script'>
>>> re.search(r'\*.script', 'a.script')
>>> re.search(r'\\*.script', 'a.script')
<re.Match object; span=(1, 8), match='.script'>
>>> re.search(r'\\\\*.script', 'a.script')
>>> re.search(r'\\\*.script', 'a.script')
>>> re.search('\\*.script', 'a.script')
>>>

When I escape the *, there is no match. When I escape it twice, only .script is matched. How can I use *.script as regex and match the full string a.script?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Orange
  • 33
  • 1
  • 5

1 Answers1

0

Try this pattern: r".*\.script". (It will match anything that ends in .script).

You need to escape the . if you want to match the char .. If you don't escape it you will match any char. . Has a special meaning inside a regex!

To get what you asked using search you just have to index with []:

re.search(r".*\.script", 'a.script')[0]

vmp
  • 2,370
  • 1
  • 13
  • 17
  • `re.search(r"\\*\.script", 'a.script')` `` How can we get a full match `a.script`? – Orange Jan 30 '21 at 01:55
  • Also, how can I force it to match from the beginning of the string to the end? When I use ^ character, it doesn't force it to match from the start. `re.search(r"\\*\.script$", 'a.script')` `` `re.search(r"^\\*\.script$", 'a.script')` Suprisingly, `$` works. – Orange Jan 30 '21 at 02:01
  • There was a mistake in my regex... I misundertood your question. `\\*` is what you need to match the `*`... But if you want to match any amount of chars you achieve it with `.*`. Check the edit I made – vmp Jan 30 '21 at 02:03
  • to force matching the whole string would be: `re.search(r"^.*\.script$", 'a.script')` – vmp Jan 30 '21 at 02:05