[英]Java preg_match between brackets
在我的應用程序中,我可以使用以下字符串:
String test = "hello" + "[" + 800 + "]" + "\n" + "world" + "[" + 810 + "]";
800
和810
是隨機的。 現在,我想使用正則表達式,例如\\[(.*?)\\]
以將括號中的任何\\n
捕獲到字符串中。 這意味着得到這樣的字符串:
800\n810
如何做到這一點並獲取括號之間的所有數字數據並具有新的test
值?
Pattern pattern = Pattern.compile ( "\\[([^]]*)\\]" );
Matcher matcher = pattern.matcher(test );
test = matcher.group();
如何做到並獲得方括號之間的所有數字數據
您可以使用此正則表達式:
\[(\d+)\]
在Java中,它將是: \\\\[(\\\\d+)\\\\]
要捕獲方括號之間的任何內容,請使用:
\[([^]]*)\]
Java代碼:
Pattern p = Pattern.compile("\\[(\\d+)\\]");
Matcher m = p.matcher( test );
while (matcher.find()) {
System.out.printf("Group: " + m.group(1));
}
您也可以嘗試環顧四周 ,以獲取僅包含在方括號內的數字。
正則表達式:
(?<=\[)\d+(?=\])
Look behind for [ ---------^^^ ^^^------------Look ahead for ]
樣例代碼:
String test = "hello" + "[" + 800 + "]" + "\n" + "world" + "[" + 810 + "]";
String regex="(?<=\\[)\\d+(?=\\])";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(test);
while(matcher.find()){
System.out.println(matcher.group());
}
輸出:
800
810
要捕獲括號之間的任何內容 ,請使用以下正則表達式:
(?<=\[)[^]]+(?=\])
查看Pattern的javadoc。
您的示例將匹配"hello8\\nworld1"
-強硬的"\\r?\\n"
也可能涵蓋由兩個字符CR aka \\r
和LF aka \\n
組成的Windows行尾-
特定於正則表達式的正則表達式字符串中的反斜杠本身必須進行轉義,反斜杠。 一個令人遺憾的狀態。
點.
與行尾不匹配,但是有一個DOTALL選項可以更改此行為。 您也可以使用命令字符串(?s)
(=單行)設置DOT_ALL。
Pattern pattern = Pattern.compile("(?s)\\[(.*?)\\]");
Pattern pattern = Pattern.compile("\\[(.*?)\\]", Pattern.DOTALL);
Matcher m = pattern.matcher(".....");
//while (m.find() { } // Search in the middle
//if (m.matches()) { } // Match all
if (m.lookingAt()) { // Starting
String s = m.group(1);
}
帶有最后一個問號(.*?)
的熱切形式確保最短的匹配,當遇到]
時,不搜索其他]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.