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

前端 未结 3 757
醉梦人生
醉梦人生 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<String> results = new ArrayList<>();
            while (matcher.find()) {
                results.add(matcher.group());
            }
            System.out.println(results);
        }
    }
    

    Output: [123, 45, 678, 90]

    Ideone demo

    0 讨论(0)
  • 2021-01-26 10:40

    There are no conditionals in Java regexes.

    I want a regex that checks if there are the same amount of regex's at the end as there are in the beginning. The conditional part: If there are x's at the beginning, then check if there are that many at the end, if there are then it is a match.

    This may or may not be solvable. If you want to know if a specific string (or pattern) repeats, that can be done using a back reference; e.g.

       ^(\d+).+\1$
    

    will match a line consisting of an arbitrary number digits, any number of characters, and the same digits matched at the start. The back reference \1 matches the string matched by group 1.

    However if you want the same number of digits at the end as at the start (and that number isn't a constant) then you cannot implement this using a single (Java) regex.

    Note that some regex languages / engines do support conditionals; see the Wikipedia Comparison of regular-expression engines page.

    0 讨论(0)
  • 2021-01-26 10:48

    I would like to use split which accept regex like so :

    String[] split = nums.split("\\s+"); // ["42", "36", "23827"]
    

    If you want to use Pattern with Matcher, then you can use String \b\d+\b with word boundaries.

    String regex = "\\b\\d+\\b";
    

    By using word boundaries, you will avoid cases where the number is part of the word, for example "123 a4 5678 9b" you will get just ["123", "4578"]

    0 讨论(0)
提交回复
热议问题