Java - 如何使用匹配器编写可选的正则表达式模式

标签 java regex

假设我正在循环遍历一个文本文件,并遇到以下两个带有随机单词和整数值的字符串

“foo 11 25”
“foo 38 15 976 24”

我编写了一个匹配两个字符串的正则表达式模式,例如:

((?:[a-z][a-z]+)\\s+\\d+\\s\\d+)

但是,问题是我认为这个正则表达式不允许我获取第二个字符串中的所有 4 个整数值。

Q1.)如何创建一个单一模式,使第三个和第四个整数可选?

Q2.) 如何编写匹配器代码,使其仅在模式找到第三个和第四个值后才进行匹配?

这里有一个模板程序,可以帮助任何愿意伸出援手的人。谢谢。

public void foo(String fooFile) {
        //Assume fooFile contains the two strings
        //"foo 11 25";
        //"foo 38 976 24";

        Pattern p = Pattern.compile("((?:[a-z][a-z]+)\\s+\\d+\\s\\d+)", Pattern.CASE_INSENSITIVE);

        BufferedReader br  = new BufferedReader(new FileReader(fooFile));
        String line;
        while ((line = br.readLine()) != null) {
            //Process the patterns
            Matcher m1 = p.matcher(line);
            if (m1.find()) {
                int int1, int2, int3, int4;
                //Need help to write the matcher code
            }
        }
    }

最佳答案

如果你想检索每个 int 值,你可以使用正则表达式:

[a-z]+\s(\d+)\s(\d+)\s?(\d+)?\s?(\d+)?

DEMO

并且每个 int 都将分为 1 到 4 组。然后您可以使用类似以下内容的内容:

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args){
        String[] strings = {"foo 11 25","foo 67 45 97",
        "foo 38 15 976 24"};

        for(String string : strings) {
            ArrayList<Integer> numbers = new ArrayList<Integer>();
            Matcher matcher = Pattern.compile("[a-z]+\\s(\\d+)\\s(\\d+)\\s?(\\d+)?\\s?(\\d+)?").matcher(string);
            matcher.find();
            for(int i = 0; i < 4; i++){
                if(matcher.group(i+1) != null) {
                     numbers.add(Integer.valueOf(matcher.group(i + 1)));
                }else{
                    System.out.println("group " + (i+1) + " is " + matcher.group(i+1));
                }
            }
            System.out.println("Match from string: "+ "\""+ string + "\"" + " : " + numbers.toString());
        }
    }
}

输出:

group 3 is null
group 4 is null
Match from string: "foo 11 25" : [11, 25]
group 4 is null
Match from string: "foo 67 45 97" : [67, 45, 97]
Match from string: "foo 38 15 976 24" : [38, 15, 976, 24]

另一种方法是将所有 int 放入一个组中:

[a-z]+\s((?:\d+\s?)+)

DEMO

并用空格分割matcher.group(1),您将得到带有值的String[]。 Java 实现:

public class Test {

    public static void main(String[] args){
        String[] strings = {"foo 11 25","foo 67 45 97",
        "foo 38 15 976 24"};

        for(String string : strings) {
            ArrayList<Integer> numbers = new ArrayList<Integer>();
            Matcher matcher = Pattern.compile("[a-z]+\\s((?:\\d+\\s?)+)").matcher(string);
            matcher.find();
            String[] nums = matcher.group(1).split("\\s");
            for(String num : nums){
                numbers.add(Integer.valueOf(num));
            }
            System.out.println("Match from string: "+ "\""+ string + "\"" + " : " + numbers.toString());
        }
    }
}

输出:

Match from string: "foo 11 25" : [11, 25]
Match from string: "foo 67 45 97" : [67, 45, 97]
Match from string: "foo 38 15 976 24" : [38, 15, 976, 24]

关于Java - 如何使用匹配器编写可选的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33027500/

相关文章:

java - 使用 FragmentStatePagerAdapter 通过 ViewPager 保留 fragment 的位置

匹配正数的正则表达式

javascript - 用于至少一个字母表 (A-z) 的名称验证的正则表达式

regex - Haskell中原始但有效的grep克隆?

python - 如何仅删除字符串中单个单词周围的括号

java - 将 JLabel 与 JCheckBox 的文本对齐

java - hibernate : StackOverflowException logging ManyToMany association

java - 如何填充包含另一个 ArrayList<String> 的 ArrayList<ArrayList<String>>

java - Lombok getter setter 找不到符号

python - 为什么我的正则表达式分组没有正确分组?