我有一些像
这样的文字The quick brown [fox] jumps over the lazy [dog]
如果我使用正则表达式
\[(.*?)\]
我得到匹配
fox
dog
我正在寻找一个正则表达式,即使其中一个大括号丢失也能正常工作。
例如,如果我有这样的文字
The quick brown [fox jumps over the lazy [dog]
我希望比赛返回" dog"
更新: 另一个例子,如果我有这样的文字
The quick brown [fox] jumps over the lazy dog]
我想让比赛返回" fox"
文本可以有多个匹配,也可以缺少多个括号:(。
我还可以使用C#来完成从正则表达式匹配中得到的结果的子字符串。
答案 0 :(得分:4)
试试这个:\[[^[]*?\]
如果它包含[
字符,它将跳过所有匹配。
答案 1 :(得分:1)
在这里:\[[^\[]+?\]
它只是避免使用char类捕获[
。
答案 2 :(得分:1)
如果您计划在最近的[
和]
之间匹配除[
和]
之外的任何内容,同时捕获内部内容,请使用
\[([^][]*)]
模式详情
\[
- 文字[
([^][]*)
- 第1组捕获除[
和]
以外的0 +个字符(因为[^...]
是否定字符类并且匹配除了在类中定义的字符之外的所有字符)(此组1值可通过Regex.Match(INPUT_STRING, REGEX_PATTERN).Groups[1].Value
)]
- 文字]
(不必在字符类之外转义)请参阅regex demo,此处为C# demo:
var list = new List<string>() {"The quick brown [fox] jumps over the lazy dog]",
"The quick brown [fox] jumps over the lazy [dog]",
"The quick brown [fox jumps over the lazy [dog]"};
list.ForEach(m =>
Console.WriteLine("\nMatch: " +
Regex.Match(m, @"\[([^][]*)]").Value + // Print the Match.Value
"\nGroup 1: " +
Regex.Match(m, @"\[([^][]*)]").Groups[1].Value)); // Print the Capture Group 1 value
结果:
Match: [fox]
Group 1: fox
Match: [fox]
Group 1: fox
Match: [dog]
Group 1: dog