我想要匹配任何开始的字符串。和单词,然后选择空格后面的任何字符。
r"^\.(\w+)(?:\s+(.+)\b)?"例:
应该匹配
.just one two
.just
.blah one@nine
.blah
.jargon blah不相匹配
.jargon
如果第一组是jargon,我希望第二组是强制性的
发布于 2022-01-26 22:44:06
使用Python,您可以排除使用负前瞻性的匹配行话,然后匹配一个或更多的单词字符。
然后可选地匹配一个或更多空格字符(不包括换行符),后面至少有一个或更多没有换行符的字符。
^\.(?!jargon$)\w+(?:[^\S\n]+.+)?$模式匹配:
^开始\.匹配一个点(?!jargon$)外露匹配行话是行中唯一的词\w+匹配1+字字符(?:非捕获群[^\S\n]+.+匹配1+空格字符(不包括换行符),然后匹配除换行符以外的1+字符)?关闭非捕获组并使其成为可选的$末端示例
import re
strings = [
".just one two",
".just",
".blah one@nine",
".blah",
".jargon blah",
".jargon"
]
for s in strings:
m = re.match(r"\.(?!jargon$)\w+(?:[^\S\n]+.+)?$", s)
if m:
print(m.group())输出
.just one two
.just
.blah one@nine
.blah
.jargon blah发布于 2022-01-26 05:21:02
一种方法是使用替换来表达您的需求:
^\.(?:(?!jargon\b)\w+(?: \S+)*|jargon(?: \S+)+)$此模式表示匹配:
^ from the start of the input
\. match dot
(?:
(?!jargon\b)\w+ match a first term which is NOT "jargon"
(?: \S+)* then match optional following terms zero or more times
| OR
jargon match "jargon" as the first term
(?: \S+)+ then match mandatory one or more terms
)
$ end of the input下面是一个示例Python脚本:
inp = [".just one two", ".just", ".blah one@nine", ".blah", ".jargon blah", "jargon"]
matches = [x for x in inp if re.search(r'^\.(?:(?!jargon\b)\w+(?: \S+)*|jargon(?: \S+)+)$', x)]
print(matches) # ['.just one two', '.just', '.blah one@nine', '.blah', '.jargon blah']发布于 2022-01-26 07:43:02
您可以尝试匹配以下正则表达式:
^\.(?!jargon$)\w+(?= .|$).*如果成功,这将匹配整个字符串。如果只想知道字符串是否符合需求,则可以删除.*。
(?!jargon$)是一个负前瞻,它断言句点不是紧跟在字符串末尾的'jargon'。
(?= .|$)是一种积极的前瞻性,它断言单词字符串后面跟着空格,后面跟着任何字符,或者它们终止字符串。
https://stackoverflow.com/questions/70858884
复制相似问题