如何检查 Java 中的字符串是否等于正则表达式模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21395110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:27:03  来源:igfitidea点击:

How to check a string in Java equals to a regex pattern?

javaregex

提问by user3001301

Lets say I have a string and it could be

假设我有一个字符串,它可能是

1234

1234

or

或者

12 34

12 34

or

或者

1 2 3 4 5

1 2 3 4 5

It doesn't matter about the number of digits or whitespace, just so that it accepts a string that has only digits and if there is whitespace within string of digits it will still accept it. How would I write the regex pattern for this?

数字或空格的数量无关紧要,只要它接受一个只有数字的字符串,如果数字字符串中有空格,它仍然会接受它。我将如何为此编写正则表达式模式?

回答by Dawood ibn Kareem

If it's acceptable to have only whitespace, then the regexp you want is "[\\d\\s]+"

如果只有空格是可以接受的,那么你想要的正则表达式是 "[\\d\\s]+"

If there has to be one or more digits, then you could use "\\s*(\\d\\s*)+"

如果必须有一个或多个数字,那么你可以使用 "\\s*(\\d\\s*)+"

Note that I've doubled up the backslashes, assuming you're writing this in Java source, rather than reading it in from some other source of text. The actual regexp in the second case is \s*(\d\s*)+

请注意,我已将反斜杠加倍,假设您是用 Java 源代码编写的,而不是从其他文本源读取它。第二种情况下的实际正则表达式是\s*(\d\s*)+

回答by Bohemian

Use String#matches()and a regex:

使用String#matches()和正则表达式:

if (str.matches("[\d\s]+"))
    // string is acceptable