对于正则表达式,搜索直至但不包括的语法是什么?类似于:
Haystack:
The quick red fox jumped over the lazy brown dog
Expression:
.*?quick -> and then everything until it hits the letter "z" but do not include z
对于正则表达式,搜索直至但不包括的语法是什么?类似于:
Haystack:
The quick red fox jumped over the lazy brown dog
Expression:
.*?quick -> and then everything until it hits the letter "z" but do not include z
表达“搜索到X
但不包括X
”的明确方式是:
(?:(?!X).)*
其中X
可以是任何正则表达式。
然而,在您的情况下,这可能过于复杂 - 在这里最简单的方法是
[^z]*
这将匹配除了 z
以外的任何字符,并因此停在下一个 z
前面。
所以 .*?quick[^z]*
将匹配 The quick fox jumps over the la
。
然而,一旦你需要查找不止一个简单字母时,(?:(?!X).)*
就会发挥作用,例如
(?:(?!lazy).)*
- 匹配任何东西直到单词 lazy
的开头。
这是使用了一个前瞻断言,更具体地说是负向前瞻。
.*?quick(?:(?!lazy).)*
将匹配 The quick fox jumps over the
。
解释:
(?: # Match the following but do not capture it:
(?!lazy) # (first assert that it's not possible to match "lazy" here
. # then match any character
)* # end of group, zero or more repetitions.
\bfox\b
只会匹配完整的单词fox
,而不是在foxy
中的fox。(?s)
来实现这一点,但并不适用于所有正则表达式引擎(特别是JavaScript)。*
量词后面添加一个?
,它将尝试从当前位置尽可能少地匹配字符:.*?(?=(?:X)|$)
将匹配任意数量的字符,停在X
(可以是任何正则表达式)或字符串结尾之前(如果X
不匹配)。您可能还需要设置“点匹配所有”选项才能使其工作。(注意:我添加了一个非捕获组来可靠地将X
与交替分隔开)
.*?quick.*?(?=z)
(?=z)
前面的 .*?
懒惰匹配:该表达式匹配子字符串直到第一次出现 z
字母。这里是 C# 代码示例:
const string text = "The quick red fox jumped over the lazy brown dogz";
string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la
string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog
试试这个
(.*?quick.*?)z
grep
时不起作用,但是这个答案可以。 - Alexandre Lavoiegrep
来过滤mysql bin转换为sql的请求,只保留一个数据库。这是命令:grep -Po "(?s)use database_to_keep(.*?)(?=^use)" mysql-bin.000045.sql > filtered.sql
- Alexandre Lavoie上箭头
键时,最后一个命令不是我使用的那个:grep -Po"(?s)use database_to_keep(.*?)(?:(?!^use).)*"mysql-bin.000045.sql>filtered.sql
。 - Alexandre Lavoie(.*?)
这部分是正确的。 - Alexandre Lavoie$
替代方案:将.*?(?=X)
替换为.*?(?=X|$)
。 - Wiktor Stribiżew