gpt4 book ai didi

python - 非连字词的正则表达式匹配

转载 作者:行者123 更新时间:2023-12-04 00:23:27 27 4
gpt4 key购买 nike

我正在尝试在 Python 中为非连字符的单词创建一个正则表达式,但我无法找出正确的语法。

正则表达式的要求是:

  1. 不应包含连字符 AND
  2. 它应该至少包含 1 个数字

我试过的表达式是:=

^(?!.*-)

  • 这匹配所有非连字符的单词,但我无法弄清楚如何另外添加第二个条件。

^(?!.*-(?=/d{1,}))

  • 我尝试使用双重先行,但我不确定要使用它的语法。这匹配 ID101 但也匹配 STACKOVERFLOW

应该匹配的示例词:1DRIVE , ID100 , W1RELESS

不应匹配的示例词:基本上任何非数字字符串(如 STACK 、 OVERFLOW )或任何带连字符的单词( Test-11 、 24-hours )

附加信息:

我正在使用库 re 并编译正则表达式模式并使用 re.search 进行匹配。

任何帮助都会非常有帮助,因为我是正则表达式匹配的新手,并且在这上面停留了好几个小时。

最佳答案

也许,

(?!.*-)(?=.*\d)^.+$

可能只是工作正常。

测试

import re

string = '''
abc
abc1-
abc1
abc-abc1
'''

expression = r'(?m)(?!.*-)(?=.*\d)^.+$'


print(re.findall(expression, string))

输出

['abc1']

如果您想简化/修改/探索表达式,在regex101.com 的右上面板中已对此进行了解释.如果你愿意,也可以在this link观看。 ,它将如何与一些样本输入相匹配。


正则表达式电路

jex.im可视化正则表达式:

enter image description here

正则表达式 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, as many times as possible, 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, as many times as possible, 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)

关于python - 非连字词的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870161/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com