也许
(?!.*-)(?=.*\d)^.+$
可能可以正常工作。
测试
import re
string = '''
abc
abc1-
abc1
abc-abc1
'''
expression = r'(?m)(?!.*-)(?=.*\d)^.+$'
print(re.findall(expression,string))
输出
['abc1']
如果您希望简化/修改/探索表达式,请在regex101.com的右上角进行说明。如果愿意,您还可以在this link中查看它如何与某些示例输入匹配。
RegEx电路
jex.im可视化正则表达式:
RegEx 101解释
/
(?!.*-)(?=.*\d)^.+$
/
gm
Negative Lookahead (?!.*-)
Assert that the Regex below does not match
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times,as many times as possible,giving back as needed (greedy)
- matches the character - literally (case sensitive)
Positive Lookahead (?=.*\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times,giving back as needed (greedy)
\d matches a digit (equal to [0-9])
^ asserts position at start of a line
.+ matches any character (except for line terminators)
+ Quantifier — Matches between one and unlimited times,giving back as needed (greedy)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
,
我想出了-
^[^-]*\d[^-]*$
- 所以我们至少需要一位数字(
\d
)
- 我们需要字符串的其余部分包含任何内容,但是--(
[^-]
)
- 我们可以无限多个字符,所以
[^-]*
- 但是像
[^-]*\d
那样将它们放在一起会在aaa3-
上失败,因为-在有效的匹配之后出现-请确保在我们的匹配^[-]*\d$
之前或之后没有破折号可以溜进来
-
不幸的是,这意味着aaa555D
失败。因此,实际上我们需要再次添加第一组-^[^-]*\d[^-]$
---表示开始-任意数量的非破折号-一个数字-任意数量的非破折号-结束
-
根据样式,我们也可以执行^([^-]*\d)+$
,因为数字/数字的顺序无关紧要,我们可以根据需要选择任意数量的数字。
但是,最后...这是我将实际解决此特定问题的方法,因为正则表达式可能功能强大,但是它们会使代码更难以理解...
if ("-" not in text) and re.search("\d",text):
本文链接:https://www.f2er.com/3097932.html