-2

Using Python 3.9 on MacOS (if it matters) I have the following boolean test that uses regular expressions to search for a pattern in a string:

found = bool(re.search(pattern, string, re.IGNORECASE))

This boolean is not a literal search. For example, the strings Z97.11 and Z98.811 come back with a pattern of .1. And that is correct for a regular expression - but I want the boolean to be true with Z97.11 only and not Z98.811 for a literal search using re.search.

The literal search also has to be case insensitive.

Hahnemann
  • 3,958
  • 6
  • 38
  • 59
  • 1
    You should use `\.1` instead, I guess. Because `.1` is indicating *ANYTHING* followed by number `1`. But `\.1` indicates the dot followed by `1`. I guess that's your case. – Amirhossein Kiani Mar 18 '22 at 22:17
  • 2
    It's quite unclear what you're actually asking us. Your question title doesn't seem to be really related to what your problem is, since you're not having issues with case. You should provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), including your desired pattern and string to test on, and the expected output, so we really know what's happening. While Amirhossein's guess as to your problem may be accurate, it's still just a guess, cause we have no idea what's really going on. – Jack Avante Mar 18 '22 at 22:20
  • **Duplicate of [Regular expression to match a dot](https://stackoverflow.com/questions/13989640/regular-expression-to-match-a-dot)** – Wiktor Stribiżew Mar 19 '22 at 11:44
  • Does this answer your question? [Regular expression to match a dot](https://stackoverflow.com/questions/13989640/regular-expression-to-match-a-dot) – Ryszard Czech Mar 19 '22 at 21:36

2 Answers2

1

If you're regular expression contains . without a backslash preceding it, then you're matching any character. So searching for .1 against 81 will succeed.

change .1 to \1. in your regular expression, and only Z97.11 should come through.

very useful resource: https://regex101.com/

Richard Dodson
  • 843
  • 2
  • 12
0

Your regular expression would be \.1 if you're looking for the presence of the literal substring .1. . has a special meaning in regex (it means any character except newline). Using a backslash (\) will escape the special meaning of the . character in regex.

found = re.search(r"\.1", string, re.IGNORECASE) is not None

I normally prefer to test out my regex patterns at regexr.com to help quickly write these expressions. I hope this site helps you too!

Example of using RegExr.com

bms
  • 1