检索所有与正则表达式模式匹配的实例。

huangapple go评论67阅读模式
英文:

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(&quot;St(?s)(.*)En&quot;);
Matcher matc = patt.matcher(vartext);
boolean found = false;
while (matc.find()) {
    found = true;
    Log.d(&quot;LogCalc&quot;, matc.group());
} 
if (!found) {
    Log.d(&quot;LogCalc&quot;, &quot;Nothing&quot;);
}

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 &amp; 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&mdash;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&mdash;a 0 will return the entire match, similar to what you currently have.

Matcher#group (Java SE 20 &amp; JDK 20).

matc.group(1)

huangapple
  • 本文由 发表于 2023年6月29日 01:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定