英文:
Retrieve all instances of a regex pattern
问题
如果我运行这段代码...
Pattern patt = Pattern.compile("St(?s)(.*)En");
Matcher matc = patt.matcher(vartext);
boolean found = false;
while (matc.find()) {
found = true;
Log.d("LogCalc", matc.group(1));
}
if (!found) {
Log.d("LogCalc", "Nothing");
}
我会得到整个字符串。我认为这是因为第一个字符串从 St
开始,最后一个字符串在 En
结束。你可以如何获取每个单独的迭代: 28828
, 217n
, 38729mdnj dnj]spw
?我认为有一种方法可以让正则表达式模式从开头开始。
英文:
I have this string (example):
<pre>
"<b>St</b> 28828 <b>En</b>, <b>St</b> 217n <b>En</b>, <b>St</b> 38729mdnj dnj]spw <b>En</b>"
</pre>
If I run this code...
Pattern patt = Pattern.compile("St(?s)(.*)En");
Matcher matc = patt.matcher(vartext);
boolean found = false;
while (matc.find()) {
found = true;
Log.d("LogCalc", matc.group());
}
if (!found) {
Log.d("LogCalc", "Nothing");
}
I get the entire string, I assume because the very first string starts at St
& the very last ends at En
. How can I get each individual iteration: 28828
, 217n
, 38729mdnj dnj]spw
? I assume there is a way to have the regex pattern start from the beginning.
Thanks,
答案1
得分: 1
以下是翻译好的部分:
_"…我得到整个字符串,我假设这是因为第一个字符串以
St
开头,最后一个以En
结尾。…"
使用 Matcher#group,如果未指定参数,它将返回整个匹配的值,而不仅仅是 捕获组。
该模式的问题在于它应该使用 懒惰量词,即 ?
。
这将匹配第一次遇到的 En
,而不是最后一次。
St(?s)(.*?)En
从这里,要返回捕获组的值,请提供数字作为值。
组编号从 1 开始,而 0 将返回整个匹配,类似于您目前的情况。
Matcher#group (Java SE 20 & JDK 20)。
matc.group(1)
英文:
> "... I get the entire string, I assume because the very first string starts at St
& the very last ends at En
. ..."
With Matcher#group, if no argument is specified, it will return the value of the entire match—not just the capturing group.
The problem with the pattern is that it should be using a lazy-quantifier, ?
.
This will match the first encountered En
, as opposed to the last.
St(?s)(.*?)En
From here, to return the value of the captured group, provide the number as a value.
Group numbers start at 1—a 0 will return the entire match, similar to what you currently have.
Matcher#group (Java SE 20 & JDK 20).
matc.group(1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论