【发布时间】:2021-11-26 14:53:52
【问题描述】:
我很尴尬我无法弄清楚,所以我不得不问。但是假设我有一个字符串 我想匹配一个或两个单词。第一个单词必须始终匹配,而第二个单词有时存在有时不存在,因此如果存在则应匹配。如果不存在,则第一个单词仍必须匹配。 IE。如果第二个单词不存在,则整个表达式不能失败。
"this <word> must always be matched and this <word1> will maybe be matched"
我天真地尝试过
(word).*(word1)?
但即使两个词都存在,也只返回<word>。如果我删除“?”返回两个单词,但如果 <word1> then 不存在,则返回“不匹配”。
~/ % pcretest
PCRE version 8.45 2021-06-15
re> "(word).*(word1)"
data> this is <word> and this is <word1>"
0: word> and this is <word1
1: word
2: word1
re> "(word).*(word1)?"
data> this is <word> and this is <word1>"
0: word> and this is <word1>"
1: word
re> "(word).*(word1)"
data> this is <word> and this is"
No match
【问题讨论】:
-
这似乎工作得很好。谢谢维克托!
标签: pcre