问题:检查字符串是否匹配模式
如何检查字符串是否与此模式匹配?
大写字母,数字,大写字母,数字…
例如,这些将匹配:
A1B2
B10L1
C1N200J1
这些不会(’^’表示问题)
a1B2
^
A10B
^
AB400
^
How do I check if a string matches this pattern?
Uppercase letter, number(s), uppercase letter, number(s)…
Example, These would match:
A1B2
B10L1
C1N200J1
These wouldn’t (‘^’ points to problem)
a1B2
^
A10B
^
AB400
^
回答 0
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
Edit: As noted in the comments match
checks only for matches at the beginning of the string while re.search()
will match a pattern anywhere in string. (See also: https://docs.python.org/library/re.html#search-vs-match)
回答 1
单线: re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
您可以bool
根据需要进行评估
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
One-liner: re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
You can evalute it as bool
if needed
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
回答 2
请尝试以下操作:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
Please try the following:
import re
name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
m = re.match("(^[A-Z]\d[A-Z]\d)", element)
if m:
print(m.groups())
回答 3
import re
import sys
prog = re.compile('([A-Z]\d+)+')
while True:
line = sys.stdin.readline()
if not line: break
if prog.match(line):
print 'matched'
else:
print 'not matched'
import re
import sys
prog = re.compile('([A-Z]\d+)+')
while True:
line = sys.stdin.readline()
if not line: break
if prog.match(line):
print 'matched'
else:
print 'not matched'
回答 4
正则表达式使这变得容易…
[A-Z]
将恰好匹配A和Z之间的一个字符
\d+
将匹配一个或多个数字
()
对事物进行分组(并且还返回事物…但是现在仅考虑将它们分组)
+
选择1个或更多
regular expressions make this easy …
[A-Z]
will match exactly one character between A and Z
\d+
will match one or more digits
()
group things (and also return things… but for now just think of them grouping)
+
selects 1 or more
回答 5
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
我认为这应该适用于大写的数字模式。
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
I believe that should work for an uppercase, number pattern.