Java:String.matches()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10261137/
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-10-31 00:16:43  来源:igfitidea点击:

Java : String.matches()

javaregexstring

提问by Predoryx

I want to determine whether a string consists of only two words, with one space character between them. The first word should only include alphanumeric characters. The second should include only numbers. An example is: asd 15

我想确定一个字符串是否只包含两个单词,它们之间有一个空格字符。第一个单词应仅包含字母数字字符。第二个应该只包含数字。一个例子是:asd 15

I would like to use String.matches. How can I do this or which regex should I use?

我想用String.matches. 我该怎么做或者我应该使用哪个正则表达式?

Thanks in advance.

提前致谢。

回答by MByD

You look for something like:

你寻找类似的东西:

String regex = "^[A-Za-z]+ [0-9]+$";

Explanation:

解释:

^         the beginning of the string (nothing before the next token)
[A-Za-z]+ at least one, but maybe more alphabetic chars (case insensitive)
          a single space (hard to see :) )
[0-9]+    at least one, but maybe more digits
$         end of the string (nothing after the digits)

回答by Juan Alberto López Cavallotti

You can give this regex a try

你可以试试这个正则表达式

"[A-Za-z0-9]+\s[0-9]+"

回答by Kannan

Try this out: String pattern = new String("^[0-9]*[A-Za-z]+ [0-9]+$")

试试这个: String pattern = new String("^[0-9]*[A-Za-z]+ [0-9]+$")