[英]Check if a String is in a specific form JAVA
Lets say I have a string 让我们说我有一个字符串
String line = "Let x0 be {1,2,3,4}"
How can I check if it the String is written in "Let ??? be ???" 如何检查String是否写在“Let ??? be ???”中
I was trying with the code below but I thing you need to know the length of the ??? 我正在尝试下面的代码,但我需要知道的长度??? to make it work
使它工作
matches = line.matches("Let \\d be \\d")
Thank you 谢谢
\\d
only match digit, short for [0-9], it can't match x0
, neither any char of "{,}"
so you can match with \\S
, which means a non-whitespace character. \\d
只匹配数字,[0-9]的缩写,它不能匹配x0
,也不能匹配"{,}"
任何字符,因此你可以匹配\\S
,这意味着一个非空白字符。 and since you do not know the length, and expect at least one, can add " +
" to \\S, like \\S+
. 并且由于你不知道长度,并且期望至少有一个,可以在\\ S中添加“
+
”,如\\S+
。 so this one can match your expect: Let \\S+ be .*
所以这个可以符合你的期望:
Let \\S+ be .*
try this regex "Let (\\w+) be (\\S+)"
试试这个正则表达式
"Let (\\w+) be (\\S+)"
String line = "Let x0 be {1,2,3,4}";
Pattern p = Pattern.compile("Let (\w+) be (\S+)");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
if(m.group(2).length> m.group(1).length){
//do something you want
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.