Introduction
我想在Java中使用RegEx提取字符串中的子字符串。为此,让我们使用模式和Matcher类来正确地完成它。
码
package stringlearning;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Jonathan
*/
public class StringLearning {
//Example String
public static String line = "This is the (first|second|third) choice.";
public static void main(String[] args)
{
//String is right, right?
System.out.println("Line is: " + line);
//How to use RegEx in Java properly
Pattern pattern = Pattern.compile("\\(([^\\)]+)\\)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(line);
//While we find, keep looping
while(matcher.find())
{
//What we foud out?
System.out.println(matcher.matches());
System.out.println(matcher.groupCount());
System.out.println(matcher.group(1));
}
}
}问题
我还是不明白它为什么找不到任何东西。正则表达式是在RegEx上创建的,并在那里正常工作(不要忘记转义!'/')
我想知道我错过了什么与不匹配
Notes
发布于 2019-09-04 17:49:25
while循环中的这一行出现了问题:
System.out.println(matcher.matches());在这里,matches()尝试将整个区域与模式匹配。
如果匹配成功,则可以通过start、end和group方法获得更多信息。
由于regex与整个输入不匹配,所以matches()返回false,您将得到代码调用.group(1)的java.lang.IllegalStateException。
要修复,只需注释掉System.out.println(matcher.matches());行并重新运行代码。
顺便说一句,您可以使用这个较短的正则表达式:
final Pattern pattern = Pattern.compile("\\(([^)]+)\\)");因为没有必要在字符类中转义),所以DOTALL在这里是多余的,因为您在正则表达式中的任何地方都没有使用DOT。
https://stackoverflow.com/questions/57793416
复制相似问题