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

前端 未结 3 764
醉梦人生
醉梦人生 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: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"]

提交回复
热议问题