gpt4 book ai didi

java - 如何使用正则表达式解析重复出现的模式

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:40:19 24 4
gpt4 key购买 nike

我想使用正则表达式在字符串中查找未知数量的参数。我认为如果我解释它会很困难,所以让我们看看这个例子:

正则表达式:@ISNULL\('(.*?)','(.*?)','(.*?)'\)
字符串:@ISNULL('1','2','3')
结果:

Group[0] "@ISNULL('1','2','3')" at 0 - 20 
Group[1] "1" at 9 - 10
Group[2] "2" at 13 - 14
Group[3] "3" at 17 - 18

效果很好。当我需要找到未知数量的参数(2 个或更多)时,问题就出现了。

我需要对正则表达式做哪些更改才能找到将出现在字符串中的所有参数?

所以,如果我解析这个字符串 "@ISNULL('1','2','3','4','5','6')" 我会发现所有的论据。

最佳答案

如果您不知道重复结构中潜在匹配的数量,您需要 regex engine that supports captures除了捕获组。 Only .NET and Perl 6 offer this currently.

在 C# 中:

  string pattern = @"@ISNULL\(('([^']*)',?)+\)";
string input = @"@ISNULL('1','2','3','4','5','6')";
Match match = Regex.Match(input, pattern);
if (match.Success) {
Console.WriteLine("Matched text: {0}", match.Value);
for (int ctr = 1; ctr < match.Groups.Count; ctr++) {
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
int captureCtr = 0;
foreach (Capture capture in match.Groups[ctr].Captures) {
Console.WriteLine(" Capture {0}: {1}",
captureCtr, capture.Value);
captureCtr++;
}
}
}

在其他正则表达式风格中,您必须分两步完成。例如,在 Java 中(代码片段由 RegexBuddy 提供):

首先,找到你需要的字符串部分:

Pattern regex = Pattern.compile("@ISNULL\\(('([^']*)',?)+\\)");
// or, using non-capturing groups:
// Pattern regex = Pattern.compile("@ISNULL\\((?:'(?:[^']*)',?)+\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
}

然后使用另一个正则表达式查找并遍历您的匹配项:

List<String> matchList = new ArrayList<String>();
try {
Pattern regex = Pattern.compile("'([^']*)'");
Matcher regexMatcher = regex.matcher(ResultString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}

关于java - 如何使用正则表达式解析重复出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3802617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com