简体   繁体   English

Java:使用正则表达式提取String中的各种值

[英]Java: Using Regular Expressions to Extract various number of values in a String

I want to write a function to extract various number of values from a String according to a regex pattern: 我想编写一个函数,根据正则表达式模式从String中提取不同数量的值:

Here is my function code: 这是我的功能代码:

/**
 * Get substrings in a string using groups in regular expression.
 * 
 * @param str
 * @param regex
 * @return
 */
public static String[] regexMatch(String str, String regex) {
    String[] rtn = null;
    if (str != null && regex != null) {
        Pattern pat = Pattern.compile(regex);
        Matcher matcher = pat.matcher(str);
        if (matcher.find()) {
            int nGroup = matcher.groupCount();
            rtn = new String[nGroup];
            for (int i = 0; i < nGroup; i++) {
                rtn[i] = matcher.group(i);
            }
        }
    }
    return rtn;
}

When I test it using: 当我使用以下方法测试时:

String str = "nets-(90000,5,4).dat";
String regex = "(\\d+),(\\d+),(\\d+)";
String[] rtn = regexMatch(str, regex);

I get: 我明白了:

rtn: [90000,5,4,90000,5]

How can I get rtn to be [90000,5,4] as I expected? 我怎么能像我预期的那样得到rtn [90000,5,4]?

Your array currently store 您的阵列当前存储

[0] -> 90000,5,4
[1] -> 90000
[2] -> 5

That is why you are seeing as output [90000,5,4,90000,5] . 这就是为什么你看到输出[90000,5,4,90000,5] It is because group(0) represents entire match so it returns 90000,5,4 . 这是因为group(0)表示整个匹配,因此它返回90000,5,4

What you need is match from groups 1, 2 and 3. 你需要的是第1,2和3组的匹配。

(\\d+),(\\d+),(\\d+)
   1      2      3

So change 所以改变

rtn[i] = matcher.group(i);

to

rtn[i] = matcher.group(i+1);

First, I would start the for loop with 1 so you can get the grouping you are declaring in your regex. 首先,我将以1开始for循环,这样你就可以得到你在正则表达式中声明的分组。 The loop should look like this: 循环应如下所示:

for (int i = 1; i <= nGroup; i++) {
            rtn[i] = matcher.group(i);
        }

Group 0 is known to be the entire matching string for your regex. 已知组0是正则表达式的完整匹配字符串。 The grouping is from: 分组来自:

String regex = "(\\d+),(\\d+),(\\d+)";

You would say matcher.group(1), matcher.group(2), and matcher.group(3) will give you what you want. 你会说matcher.group(1),matcher.group(2)和matcher.group(3)会给你你想要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM