[英]Regex in python: word matching if n characters in a row are equal to the pattern
[英]Regex pattern for matching "-" character but only if there are other word characters present
我有一组用于匹配的条目。 我已经写过的一种模式匹配仅由“-”组成的字符串,例如:
----
---
--------
匹配这些的正则表达式代码是
r"^[-]+$"
现在我需要匹配包含“-”字符的字符串,但前提是字符串中有其他单词字符,例如:
---vsgvrf-sgwfwrgfs---
-----hwvchwbfk
bfcbewubf------
-efefe-ege-
-gdiwen
等等。我尝试了下一个模式,但它们不起作用并跳过了一些字符串:
r"(\w[^-])+-+(\w[^-])*"
r"\w[^-]+-+\w[^-]+|-+\w[^-]+|\w[^-]+-+"
有人可以帮我吗?
使用此正则表达式(破折号之前或之后的单词字符):
r'(-\w|\w-)'
如果连字符和\w
都需要,那么:
^(?:-+\w|\w+-)[\w-]*$
如果只需要\w
以及可选数量的连字符和单词字符:
^-*\w[-\w]*$
regex101 的另一个演示(对我来说,你的问题读起来就足够了)
您可以使用((?:\w+-+|-+\w+)+\w*-*)
来完成。
import re
m = re.compile(r'((?:\w+-+|-+\w+)+\w*-*)')
lines = ['-Before', '-Before-Middle', 'Middle-After-', 'After-', '--All--Three--', 'No Match', '-', '--', '---']
for line in lines:
if m.match(line):
print(m.match(line).groups())
Output:
('-Before',)
('-Before-Middle',)
('Middle-After-',)
('After-',)
('--All--Three--',)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.