PHP中的PHP的`preg_match_all`功能 [英] PHP's `preg_match_all` functionality in Java
问题描述
在PHP中,如果我们需要匹配类似 [one,two,three]
之类的东西,我们可以使用以下正则表达式 preg_match
。
In PHP if we need to match a something like, ["one","two","three"]
, we could use the following regular expression with preg_match
.
$pattern = "/\[\"(\w+)\",\"(\w+)\",\"(\w+)\"\]/"
通过使用括号,我们还可以提取单词1,2和3。我知道Java中的 Matcher
对象,但无法获得类似的功能;我只能提取整个字符串。我将如何在Java中模仿 preg_match
行为。
By using the parenthesis we are also able to extract the words one, two and three. I am aware of the Matcher
object in Java, but am unable to get similar functionality; I am only able to extract the entire string. How would I go about mimicking the preg_match
behaviour in Java.
推荐答案
使用匹配器,要获得组,您必须使用 Matcher.group()
方法。
With a Matcher, to get the groups you have to use the Matcher.group()
method.
例如:
Pattern p = Pattern.compile("\\[\"(\\w+)\",\"(\\w+)\",\"(\\w+)\"\\]");
Matcher m = p.matcher("[\"one\",\"two\",\"three\"]");
boolean b = m.matches();
System.out.println(m.group(1)); //prints one
记住 group(0)
是相同的整个匹配序列。
Remember group(0)
is the same whole matching sequence.
资源:
- Javadoc - Matcher.group()
这篇关于PHP中的PHP的`preg_match_all`功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!