I need a regex which can match "Hello, name" pattern but the comma is optional. If the comma is not present, the number of spaces between Hello and name should be one. If the comma is present, then the number of spaces between comma and name should be one. After Hello + (comma+space or space), there should at least be one character and after that anything can follow
I tried the following regex
Hello,?\s{1}\S.*
But it also matches "Hello , name"
i.e space between Hello and comma.
>Solution :
The reason Hello,?\s{1}\S.*
matches "Hello , name"
(space after Hello) is:
Hello
matches the initial"Hello"
.- Since the comma is optional, it is not matched
\s{1}
matches the space after the"Hello"
(Note the{1}
is redundant.\s
on its own will do the same thing, match a single whitespace)\S
matches the comma.*
matches the rest of the string, i.e." name"
To prevent this, consider disallowing commas and spaces in the name Try online:
^Hello,?\s[^,\s]+$
------------------
^ $ : Start and end of string
Hello : Literal Hello
,? : Optional comma
\s : One whitespace
[^,\s]+ : One or more characters that are not comma or space
import re
strings = """Hello, Chopin
Hello Brahms
Hello, Mozart
Hello , name
Hello name
Hello Chopin""".split("\n")
for test in strings:
print(test, re.search(r"^Hello,?\s[^,\s]+$", test))
gives:
Hello, Chopin <re.Match object; span=(0, 13), match='Hello, Chopin'>
Hello Brahms <re.Match object; span=(0, 12), match='Hello Brahms'>
Hello, Mozart None
Hello , name None
Hello name None
Hello Chopin <re.Match object; span=(0, 12), match='Hello Chopin'>