Dan*_*lTA 270 python regex string-matching
如何检查字符串是否与此模式匹配?
大写字母,数字,大写字母,数字......
示例,这些将匹配:
A1B2
B10L1
C1N200J1
Run Code Online (Sandbox Code Playgroud)
这些不会('^'指向问题)
a1B2
^
A10B
^
AB400
^
Run Code Online (Sandbox Code Playgroud)
Cra*_*sta 408
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
Run Code Online (Sandbox Code Playgroud)
编辑:如评论中所述,match仅检查字符串开头的匹配项,同时re.search()匹配字符串中任何位置的模式.(另见:https://docs.python.org/library/re.html#search-vs-match)
neh*_*iah 141
一内胆: re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
Run Code Online (Sandbox Code Playgroud)
您可以bool根据需要评估它
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
Run Code Online (Sandbox Code Playgroud)
小智 33
请尝试以下方法:
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())
Run Code Online (Sandbox Code Playgroud)
Ali*_*jad 24
如果您想匹配完整的字符串,则该方法re.match(...)将不起作用。
例如;
\nre.match("[a-z]+", "abcdef")\xe2\x9c\x85 将给出匹配项re.match("[a-z]+", "abcdef 12345")\xe2\x9c\x85 也会给出匹配项,因为字符串中有一部分匹配(也许当您检查整个字符串是否有效时您不希望这样)使用re.fullmatch(...)。仅当以下情况时才会匹配
if re.fullmatch("[a-z]+", my_string):\n print("Yes")\nRun Code Online (Sandbox Code Playgroud)\nre.fullmatch("[a-z]+", "abcdef")\xe2\x9c\x85 是re.fullmatch("[a-z]+", "abcdef 12345")\xe2\x9d\x8c 否一班轮: bool(re.fullmatch("[a-z]+", my_string))
Mar*_*hen 23
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'
Run Code Online (Sandbox Code Playgroud)
cry*_*ick 22
正如评论中所述,所有这些答案都re.match在字符串的开头使用隐式匹配。re.search如果您想泛化到整个字符串,则需要。
import re
pattern = re.compile("([A-Z][0-9]+)+")
# finds match anywhere in string
bool(re.search(pattern, 'aA1A1')) # True
# matches on start of string, even though pattern does not have ^ constraint
bool(re.match(pattern, 'aA1A1')) # False
Run Code Online (Sandbox Code Playgroud)
如果您需要完整的字符串来完全匹配正则表达式,请使用以下命令查看@Ali Sajjad 的答案re.fullmatch
图片来源:评论中的@LondonRob 和@conradkleinespel。
正则表达式使这很容易......
[A-Z] 将恰好匹配A和Z之间的一个字符
\d+ 将匹配一个或多个数字
() 分组的东西(还有东西......但是现在只想到它们分组)
+ 选择1个或更多
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
我相信这应该适用于大写的数字模式.