在匹配数字之前,您可以选择匹配 $
或大写字符。
(?:\$|\b[A-Z]+)?\d+
模式匹配
-
(?:
非捕获组
-
\$
匹配 $
-
|
或
-
\b[A-Z]+
一个单词边界,匹配 1+ 个大写字符
-
)?
关闭非捕获组并使其成为可选
-
\d+
匹配 1 个以上的数字
Regex demo | Python demo
示例
import re
test = 'We four guys,live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = re.findall(r'(?:\$|\b[A-Z]+)?\d+',test)
print(arr)
输出
['2','$248','ABC1234']
如果不想只匹配数字,则非捕获组不应该是可选的,可以在末尾添加词边界\b
以防止部分匹配:
(?:\$|\b[A-Z]+)\d+\b
Regex demo | Python demo
import re
test = 'We four guys,live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = re.findall(r'(?:\$|\b[A-Z]+)\d+\b',test)
print(arr)
输出
['$248','ABC1234']
,
我使用此代码将 $ 和 ABC 组合在一起:
import re
test = 'We four guys,live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = []
arr = re.findall(r'(?:\$|ABC)[0-9]+',test)
print(arr)
结果是['$248','ABC1234']
,
我相信 re
符号不需要 $
模块。因为您可以使用内置的 Python 方法 - .startswith
和 .endswith
。这是你如何使用它 -
test = '...'
for i in test.split():
if i.startswith('$'):
print('With $ sign: ',i)
if i.startswith('ABC'):
print('With ABC: ',i)
您也可以使用 .startswith
作为序列号。但是,如果序列号中的字母是随机的并且不是以“ABC”开头的总是,则可以使用 re
。所以,你需要匹配后面有数字的字符串,然后你可以这样做 -
a = re.findall(r'[a-z]+[\d]+|[A-Z]+[\d]+',test)
print(a)
这里,
[a-z]+[\d]+
匹配任何带有小写字母和数字的字符串。 例如-abc1200、ABC1234。如果您不需要小写字母,请将它们删除。但是,为了确保安全,我添加了它们。
|
是正则表达式中的 Or
运算符
[A-Z]+[\d]+
匹配任何带有大写字母和数字的字符串。这是您需要的模式的主要部分。
正如我所说,如果您不需要匹配的小写字母,则删除 [a-z]+[\d]+
和 |
所以,
'$' 使用 .startswith
,'Serial Numbers' 使用 re
本文链接:https://www.f2er.com/77661.html