有沒有人知道如何解析下面的字符串來獲取這兩個字符串:[Test1][Test2]
和[Test3][Test4]
。如何解析正則表達式
STRING:
Hello [Test1][Test2] world] [Test3][Test4] this is test].
有沒有人知道如何解析下面的字符串來獲取這兩個字符串:[Test1][Test2]
和[Test3][Test4]
。如何解析正則表達式
STRING:
Hello [Test1][Test2] world] [Test3][Test4] this is test].
你將不得不做一個循環來獲得動態數量的匹配(我想你想得到)。
我使用了.*?((?:\[.*?\])+)(.*)
的模式。第一個匹配組將找到所需的字符串,第二個匹配組將始終找到「其餘」,您將不得不再次解析。
構造「(?:...)」是一個非捕獲組,它不會產生匹配組(在Java正則表達式語法中)。
這裏是一個簡短的Java樣本:
public static void main(String[] args) {
// define regular expression
Pattern pattern = Pattern.compile(".*?((?:\\[.*?\\])+)(.*)");
// iterate for each match
Matcher matcher = pattern.matcher("Hello [Test1][Test2] world] [Test3][Test4] this is test].");
while (matcher.matches()) {
String text = matcher.replaceFirst(matcher.group(2));
System.out.println("Found " + matcher.group(1));
matcher = pattern.matcher(text);
}
}
這將輸出:
Found [Test1][Test2]
Found [Test3][Test4]
很抱歉,如果這是一種複雜的,請讓我/我們知道,如果你需要一個簡單的例子。 ..
使用perl
味正則表達式:
m/\[\S+/g
測試:
的script.pl
內容:
use warnings;
use strict;
## Read all data after __DATA__ filehandle.
while (<DATA>) {
## Save in array '@matches' any characters from an opening
## square bracket until a blank found.
## 'g' flag means to do it many times in same line.
my @matches = m/\[\S+/g;
## Print to output. Each match in a line.
printf qq[%s\n], join qq[\n], @matches;
}
__DATA__
Hello [Test1][Test2] world] [Test3][Test4] this is test].
運行腳本:
perl script.pl
結果:
[Test1][Test2]
[Test3][Test4]
更普遍的怎麼樣? kdzwinel的答案適用於上述示例。如果你需要解決更復雜的輸入數據,你應該改善這個問題,用戶不是大寫的。請幫助我們幫助你。 – 2012-01-16 16:29:50