我是 Java 正则表达式的新手。我喜欢使用正则表达式提取字符串。
这是我的字符串:“Hello,World”
我喜欢提取“,”之后的文本。结果将是“世界”。我试过这个:
final Pattern pattern = Pattern.compile(",(.+?)");
final Matcher matcher = pattern.matcher("Hello,World");
matcher.find();
但是下一步会是什么?
你不需要正则表达式。您可以简单地以逗号分隔并从数组中获取第二个元素:-
System.out.println("Hello,World".split(",")[1]);
输出: -
World
但是如果你想使用Regex
,你需要?
从你的正则表达式中删除。
?
after+
用于Reluctant
匹配。它只会匹配W
并停在那里。你在这里不需要那个。你需要匹配,直到它可以匹配。
所以改用greedy
匹配。
这是修改过的正则表达式的代码: -
final Pattern pattern = Pattern.compile(",(.+)");
final Matcher matcher = pattern.matcher("Hello,World");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
输出: -
World
扩展你所拥有的,你需要删除? 从您的模式签名以使用贪婪匹配,然后处理匹配的组:
final Pattern pattern = Pattern.compile(",(.+)"); // removed your '?'
final Matcher matcher = pattern.matcher("Hello,World");
while (matcher.find()) {
String result = matcher.group(1);
// work with result
}
其他答案为您的问题提出了不同的方法,并可能为您的需要提供更好的解决方案。
System.out.println( "Hello,World".replaceAll(".*,(.*)","$1") ); // output is "World"
您正在使用不情愿的表达式,只会选择一个字符W
,而您可以使用贪婪的表达式并打印匹配的组内容:
final Pattern pattern = Pattern.compile(",(.+)");
final Matcher matcher = pattern.matcher("Hello,World");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
输出:
World
请参阅正则表达式模式文档