Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java字符串正则表达式_Java_Regex - Fatal编程技术网

Java字符串正则表达式

Java字符串正则表达式,java,regex,Java,Regex,团队, 我有一个任务。i、 例如,我想在一堆数据中检查98%。 我试图写一些正则表达式,但它给出了连续的错误 String str="OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked."; if(str.matches("[0-9][0-9]%")) 但它正在返回错误 非常感谢您的回复。使用pattern/matcher/find方法匹配将正则表达式应用于整个字符串 Pattern pattern =

团队, 我有一个任务。i、 例如,我想在一堆数据中检查
98%
。 我试图写一些正则表达式,但它给出了连续的错误

String str="OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
if(str.matches("[0-9][0-9]%"))
但它正在返回错误


非常感谢您的回复。

使用pattern/matcher/find方法
匹配
将正则表达式应用于整个字符串

Pattern pattern = Pattern.compile("[0-9]{2}%");
String test = "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(test);
if(matcher.find()) {
    System.out.println("Matched!");
}

使用pattern/matcher/find方法
匹配
将正则表达式应用于整个字符串

Pattern pattern = Pattern.compile("[0-9]{2}%");
String test = "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(test);
if(matcher.find()) {
    System.out.println("Matched!");
}
尝试:

或(
\d
=数字):

匹配模式还应该匹配
98%
之前/之后的字符,这就是为什么要添加
*

评论:
你可以像其他人建议的那样使用模式匹配器,如果你想从字符串中提取
98%
,它特别有效,但是如果你只是想找到是否有匹配项,我发现
.matches()
使用起来更简单。

试试:

或(
\d
=数字):

匹配模式还应该匹配
98%
之前/之后的字符,这就是为什么要添加
*

评论:

你可以像其他人建议的那样使用模式匹配器,如果你想从字符串中提取
98%
,它特别有效,但是如果你只是想找到是否有匹配项,我发现
.matches()
使用起来更简单。

你可以试试这个正则表达式
\d{1,2}(\.\d{0,2})?%
这将匹配
98%
或百分比与十进制值,如
98.56%

Pattern pattern = Pattern.compile("\\d{1,2}(\\.\\d{0,2})?%");
String yourString= "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()) {
    System.out.println(matcher.group());
}

您可以尝试使用这个正则表达式
\d{1,2}(\.\d{0,2})%%
这将匹配
98%
或带有十进制值的百分比,如
98.56%

Pattern pattern = Pattern.compile("\\d{1,2}(\\.\\d{0,2})?%");
String yourString= "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()) {
    System.out.println(matcher.group());
}

str.matches(“[0-9][0-9]]”)
实际上应用了这个正则表达式
^[0-9][0-9]$
,它被锚定在开始和结束处。其他人已经描述了这方面的解决方案。

str.matches(“[0-9][0-9]]”
实际上应用了这个正则表达式,它被锚定在开始和结束处。其他人已经介绍了解决方案。

@user1835935欢迎使用Stackoverflow!如果答案有帮助,你应该选择其中一个,点击问题左上角的V(复选标记)来“接受”。你应该对你发布的其他问题也这样做。如果您发现多个答案有帮助(您只能接受一个),您可以通过单击“向上箭头”向上投票其他有帮助的答案。@user1835935欢迎使用Stackoverflow!如果答案有帮助,你应该选择其中一个,点击问题左上角的V(复选标记)来“接受”。你应该对你发布的其他问题也这样做。如果您发现多个答案有帮助(您只能接受一个),您可以通过单击“向上箭头”向上投票其他有帮助的答案。