[英]find the start of a matched region (java regex)
假設我感興趣的字符串類似於這些num3.a
, num4.b
等(但我不希望它匹配這些foo.num3.a
, whatever.num2.b
)
我有這個正則表達式來匹配它們Pattern p = Pattern.compile("[^\\\\.]\\\\bnum(\\\\d*)(?=\\\\.)";
鑒於此輸入字符串: (num3.a)
Matcher m = p.matcher("(num3.a)");
if (m.find())
System.out.println(m.start()); // This would print 0 rather than 1 WHY?
如何更改代碼使其打印1
? (因為1
是n
的索引,這是我感興趣的模式的開始)
如果您對 num3.a 感興趣,您應該擴展您的組。 括號表示一個組,可用於在匹配中尋址。
[^\\\\.]\\\\b(num\\\\d*)(?=\\\\.)
然后你可以訪問該組
start(0)
和end(0)
Pattern p = Pattern.compile("\\b(num\\d*\\.a)");
String input = "fffffffffffff(num3.a)fffffffffffffffffsdfsdf";
Matcher m = p.matcher(input);
if (m.find())
{
System.out.println(m.start(0));
System.out.println(input.substring(m.start(0), m.end(0)));
}
會輸出
14
num3.a
報告此匹配器區域的起始索引。
這並不表示匹配的開始,僅表示檢查匹配的區域的開始。
使用find()
和start()
來查找匹配的開始。
現在你改變了你的模式。 [^\\\\.]
匹配任何不是點的東西。 A (
兩者都不是,所以它是匹配的。 (
在給定的String
位於索引 0 處。
Pattern p = Pattern.compile("\\,\\d*");
String inpu = "Hotel Class : 5,106936 ";
Matcher m = p.matcher(inpu);
if (m.find())
{
System.out.println(inpu.substring(m.start(0), m.end(0)));
}
輸出為“5,106936”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.