-2

It is not a duplicate question, other questions are about the repetition of a regex and my question is how can we get/limit a particular character count in regex for validation, I am looking for a regex to match a string only when the string has the count of character ' as 1. Example:

patt = #IDontKnow
s = "Shubham's"
if re.match(patt, s):
    print ("The string has only ONE '")
else:
    print ("The String has either less or more than ONE ' count")

2 Answers2

0

Why not just use .count()?

s = "Shubham's"
if s.count("\'") == 1:
    print ("The string has only ONE '")
else:
    print ("The String has either less or more than ONE ' count")
Mark
  • 5,089
  • 2
  • 20
  • 31
0

I guess what you are looking for is this:

import re
pat = "^[^\']*\'[^\']*$"
print (re.match(pat, "aeh'3q4'bl;5hkj5l;ebj3'"))
print (re.match(pat, "aeh3q4'bl;5hkj5l;ebj3'"))
print (re.match(pat, "aeh3q4bl;5hkj5l;ebj3'"))
print (re.match(pat, "'"))
print (re.match(pat, ""))

Which gives output:

None
None
<_sre.SRE_Match object; span=(0, 21), match="aeh3q4bl;5hkj5l;ebj3'">
<_sre.SRE_Match object; span=(0, 1), match="'">
None

What "^[^\']*\'[^\']*$" does?

^ matches the beginning of string

[^\']* - * matches 0 or more characters from set defined in []. Here, we have a set negated using ^. The set is defined as one character - ', which is escaped so it looks \'. Altogether, this group matches any number of any characters except '

\' - matches one and only character '

$ - matches end of the string. Without it partial matches would be possible which could contain more ' characters. You can compare with above:

print (re.match("^[^\']*\'[^\']*", "aeh'3q4'bl;5hkj5l;ebj3'"))

<_sre.SRE_Match object; span=(0, 7), match="aeh'3q4">
sophros
  • 14,672
  • 11
  • 46
  • 75