Here I am try to match the specific characters in a string,
^[23]*$
Here my cases,
2233
--> Match22
--> Not Match33
--> Not Match2435
--> Not Match2322
--> Match323
--> MatchI want to match the string with correct regular expression. I mean 1,5,6 cases needed.
Update:
If I have more than two digits match, like the patterns,
234
or 43
or etc. how to match this pattern with any string ?.
I want dynamic matching ?
How about:
(2+3|3+2)[23]*$
String must either:
Update: to parameterize the pattern
To parameterize this pattern, you could do something like:
x = 2
y = 3
pat = re.compile("(%s+%s|%s+%s)[%s%s]*$" % (x,y,y,x,x,y))
pat.match('2233')
Or a bit clearer, but longer:
pat = re.compile("({x}+{y}|{y}+{x})[{x}{y}]*$".format(x=2, y=3))
Or you could use Python template strings
Update: to handle more than two characters:
If you have more than two characters to test, then the regex gets unwieldy and my other answer becomes easier:
def match(s,ch):
return all([c in s for c in ch]) and len(s.translate(None,ch)) == 0
match('223344','234') # True
match('2233445, '234') # False
Another update: use sets
I wasn't entirely happy with the above solution, as it seemed a bit ad-hoc. Eventually I realized it's just a set comparison - we just want to check that the input consists of a fixed set of characters:
def match(s,ch):
return set(s) == set(ch)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句