我是Java中正则表达式的新手。我喜欢使用正则表达式来提取字符串。java的正则表达式:提取文本后的分隔符?
这是我的字符串:“你好,世界”
我想提取后的文字“”。结果将是“世界”。我试过这个:
final Pattern pattern = Pattern.compile(",(.+?)");
final Matcher matcher = pattern.matcher("Hello,World");
matcher.find();
但是下一步会是什么?
我是Java中正则表达式的新手。我喜欢使用正则表达式来提取字符串。java的正则表达式:提取文本后的分隔符?
这是我的字符串:“你好,世界”
我想提取后的文字“”。结果将是“世界”。我试过这个:
final Pattern pattern = Pattern.compile(",(.+?)");
final Matcher matcher = pattern.matcher("Hello,World");
matcher.find();
但是下一步会是什么?
你不需要这个正则表达式。你可以简单地分为上逗号,并从数组的第二个元素: - :
World
但是,如果你想使用Regex
,你需要 -
System.out.println("Hello,World".split(",")[1]);
OUTPUT从您的正则表达式中删除?
。
?
后+
用于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
,而你可以使用一个贪婪 one和p RINT您的匹配组内容:
final Pattern pattern = Pattern.compile(",(.+)");
final Matcher matcher = pattern.matcher("Hello,World");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
输出:
World