如何只找到带有正则表达式的整数?

给定以下字符串:

11 bsszzz 0.5 te 11.43 432 -66 a x 

我想找到所有的整数。在这种情况下:11,432-66

我可以为此使用哪个正则表达式?

我试过-?d+,但它会返回每个数字,包括那些是十进制数字的一部分。

编辑:

以下重复目标均未回答该问题:

  1. 重复目标中的解决方案Regex to Match only integer给出11432、 和66不满足要求。
  2. 在复制目标的解决方案,Python的正则表达式匹配的整数但不漂浮太给出了相同的输出,即1143266

事实上,两个重复的目标是彼此重复的,但没有一个满足这个问题的要求。

回答

你可以使用-?b(?<!.)d+(?!.)b哪里

  1. -? 指定可选 -
  2. b 指定词边界
  3. ?<!指定负后视并?!指定负前瞻。

演示:

import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
class Main {
    public static void main(String[] args) {
        String str="11 bsszzz 0.5 te 11.43 432 -66 a x";
        System.out.println(Pattern.compile("-?b(?<!.)d+(?!.)b")
                .matcher(str)
                .results()
                .map(MatchResult::group)                
                .collect(Collectors.toList()));
    }
}

输出:

[11, 432, -66]

  • @RyszardCzech what is the point of your comment if this regex solved my problem? Why are you adding new conditions that I don't need?
  • @RyszardCzech - There is no problem with the regex and it fulfils the requirement perfectly. The value, `20` in `Nr.20` does not qualify for the requirement. Do not misguide the visitors with a negative comment without asking the OP the relevant question. And, do that below the question, not below someone's answer. There were some comments below the question which are no more there. I trust the moderators who might have removed them for some purpose (the most common reason is a conflict or some hostile messages).
  • @RyszardCzech `Nr.20` could be taken to be either` Nr.` followed by`20` or `Nr` followed by `.20`. In the latter case it is clearly a decimal. But using your logic, the expression wouldn't find 2213 correctly because that is really 22 followed by 13 which is two integers back to back. So one needs to consider the OPs example in resolving this.

以上是如何只找到带有正则表达式的整数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>