How to make a regular expression match based on a condition?

前端 未结 3 784
醉梦人生
醉梦人生 2021-01-26 10:17

I\'m trying to make a conditional regex, I know that there are other posts on stack overflow but there too specific to the problem.


The Question

How can

3条回答
  •  难免孤独
    2021-01-26 10:31

    I do not see the "conditional" in the question. The problem is solvable with a straight forward regular expression: \b\d+\b.

    regex101 demo

    A fully fledged Java example would look something like this:

    import java.util.ArrayList;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    class Ideone {
        public static void main(String args[]) {
            final String sample = "123 45 678 90";
            final Pattern pattern = Pattern.compile("\\b\\d+\\b");
            final Matcher matcher = pattern.matcher(sample);
            final ArrayList results = new ArrayList<>();
            while (matcher.find()) {
                results.add(matcher.group());
            }
            System.out.println(results);
        }
    }
    

    Output: [123, 45, 678, 90]

    Ideone demo

提交回复
热议问题