非连接词的正则表达式匹配-Python 测试输出 RegEx电路

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

对正则表达式的要求是:

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

我尝试过的表达式是:=

  

^(?!。*-)

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

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

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

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

不匹配的示例单词: 基本上是任何非数字字符串(例如STACK,OVERFLOW)或任何带连字符的单词(Test-11,24小时制)

其他信息:

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

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

ykxsky 回答:非连接词的正则表达式匹配-Python 测试输出 RegEx电路

也许

(?!.*-)(?=.*\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可视化正则表达式:

enter image description here

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[^-]*$

  1. 所以我们至少需要一位数字(\d
  2. 我们需要字符串的其余部分包含任何内容,但是--([^-]
  3. 我们可以无限多个字符,所以[^-]*
  4. 但是像[^-]*\d那样将它们放在一起会在aaa3-上失败,因为-在有效的匹配之后出现-请确保在我们的匹配^[-]*\d$之前或之后没有破折号可以溜进来
  5. 不幸的是,这意味着aaa555D失败。因此,实际上我们需要再次添加第一组-^[^-]*\d[^-]$ ---表示开始-任意数量的非破折号-一个数字-任意数量的非破折号-结束

  6. 根据样式,我们也可以执行^([^-]*\d)+$,因为数字/数字的顺序无关紧要,我们可以根据需要选择任意数量的数字。

但是,最后...这是我将实际解决此特定问题的方法,因为正则表达式可能功能强大,但是它们会使代码更难以理解...

if ("-" not in text) and re.search("\d",text):

本文链接:https://www.f2er.com/3097932.html

大家都在问