0

It is the scenario:

Frontend pass the regular expression to backend, then backend get it and execute the regular expression. But i want to just execute the wildcard match.

For example: Frontend pass bash-1.*.0, it works well

But bash-1.(hello):*.0, it will not match bash-1.(hello):1.0

So is it possible only match wildcard by python re module?

PengQun Zhong
  • 35
  • 1
  • 8
  • 1
    `*` in a regular expression does not mean a wildcard. – kaya3 May 06 '21 at 00:51
  • Add a period before the asterisk and your second example will match – gregory May 06 '21 at 00:57
  • No it wont @gregory There is no escaping of `()` meaning there is a defined capturing group. Simply adding `.*` will not find a match. – PacketLoss May 06 '21 at 01:00
  • @PacketLoss there's no mention of a capturing group: the pattern is `bash-1.(hello):*.0` and the literal string is `bash-1.(hello):1.0`. – gregory May 06 '21 at 01:09
  • @gregory That pattern does not match. `()` is not escaped, nor is `.`. Both in `regex101` and `re` it does not match. https://regex101.com/r/PQDFky/1 – PacketLoss May 06 '21 at 02:33
  • @gregory To match `bash-1.(hello):1.0` you need to escape the `()` correctly. `bash-1\.\(hello\):.\.0` matches OP's string. – PacketLoss May 06 '21 at 02:34

3 Answers3

2

You're looking for .* . is a wildcard, and * is any number (while the comparable ? is zero or one and + is at least one)

ti7
  • 16,375
  • 6
  • 40
  • 68
0

In regex a . will match anything except line terminators once, where .* will match unlimited times.

In your current pattern, you are trying to match a . however are forgetting to escape it, meaning it will match anything. You should correctly escape the . and () then you will be able to find a match.

string = 'bash-1.(hello):1.0'
pattern = 'bash-1\.\(hello\):.\.0'
re.match(pattern, string)
#<re.Match object; span=(0, 18), match='bash-1.(hello):1.0'>

https://regex101.com/r/Wj3V7e/1

PacketLoss
  • 5,561
  • 1
  • 9
  • 27
0

You shoulde use the fnmatch module in the stdlib if you want glob-style matching. For example:

import fnmatch
print(fnmatch.fnmatch("bash-1.(hello):1.0","bash-1.(hello):*.0")) # True
print(fnmatch.fnmatch("bash-1.(goodbye):1.0","bash-1.(hello):*.0")) # False
SuperStormer
  • 4,997
  • 5
  • 25
  • 35