我一直在研究这个项目,该项目需要将文件转换为字符串,然后查找字符串中某些字符串的位置。我正在尝试使用 Pattern 和 Matcher 类来执行此操作。请看下面我的代码(java):
String begin = "TOSS-UP" + "\\s*" + j;
String end = "TOSS-UP" + "\\s*" + (j+1);
Pattern beginPattern = Pattern.compile(begin);
Pattern endPattern = Pattern.compile(end);
System.out.println(beginPattern);
Matcher beginMatcher = beginPattern.matcher(input);
Matcher endMatcher = endPattern.matcher(input);
int beginPosition = beginMatcher.start();
int endPosition = endMatcher.start();
其中 j 是 for 循环中的变量(从 1 开始,一直到 24),输入是一个字符串,如下所示:
第 1 轮 抛球 1) ... 抛球 2) ... 抛球 3) ... 抛球 4) ...
我需要使用正则表达式,因为这个字符串经常在 TOSS-UP 和数字之间有一个\n (而不是一个简单的空格)。
我是正则表达式的新手,试图从互联网示例中学习什么,但我不明白为什么这个程序无法编译。 Eclipse 给我的错误是:
Exception in thread "main" java.lang.IllegalStateException: No match available
at java.util.regex.Matcher.start
at Driver.main
任何修复正则表达式的帮助将不胜感激。如果其他人有其他解决方案,请告诉我。谢谢!
最佳答案
在尝试从匹配器对象获取任何内容之前,请先调用 matches()
函数。调用 matches()
将触发匹配,并根据是否匹配返回一个 boolean 值。
... // as usual
int beginPosition = -1;
int endPosition = -1;
if(beginMatcher.matches()) {
beginPosition = beginMatcher.start();
}
if(endMatcher.matches()) {
endPosition = endMatcher.start();
}
正如 @MikeSamuel 在评论中指出的,如果您只想要第一个匹配项,也许 .find()
会更好。另外,请考虑将 \b
添加到正则表达式的末尾,以便在 TOSS-UP 10
中找不到 TOSS-UP 1
,例如.
关于Java 正则表达式无法编译 - 无匹配可用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44532403/