我根据这篇文章完成了你的要求:
http://www.rexegg.com/regex-best-trick.html
简要概括一下,总体策略如下:
首先,你需要按照以下格式创建一个正则表达式:
NotThis | NeitherThis | (IWantThis)
接下来,你的捕获组$1将只包含你感兴趣的斜杠,以执行拆分。
然后,您可以使用一些不太可能出现的内容来替换它们,之后在这个替换后的术语中执行拆分。
因此,有了这个策略,这就是代码:
正则表达式:
\\/(?=\\/)|(?:http:\\/\\/)?www[\\w\\.\\/\\-]*(?=\\/)|(\\/)
解释:
这个术语应该是双斜杠与lookAhead(只取第一个斜杠)
\\/(?=\\/)
Neither是一个基本的URL检查术语,具有前瞻性以避免捕获最后一个\/。
(?:http:\\/\\/)?www[\\w\\.\\/\\-]*(?=\\/)
IWantThis这个术语简单来说就是斜线:
(\\/)
在Java代码中,您可以像这样将所有内容组合在一起:
Pattern p = Pattern.compile("\\/(?=\\/)|(?:http:\\/\\/)?www[\\w\\.\\/\\-]*(?=\\/)|(\\/)");
Matcher m = p.matcher("(TOP~did~1~1 (S~did~2~2 (NPB~I~1~1 I/PRP ) (VP~did~3~1 did/VBD not/RB (VP~read~2~1 read/VB (NPB~article~2~2 the/DT article/NN ./PUNC. ) ) ) ) )\n(TOP Source/NN http://www.alwatan.com.sa/daily/2007-01-31/first_page/first_page01.htm/X ./. )\n(NPB~sister~2~2 Your/PRP$ sister/NN //PUNC: )");
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, "Superman");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
System.out.println("\n" + "*** Replacements ***");
System.out.println(replaced);
String[] splits = replaced.split("Superman");
System.out.println("\n" + "*** Splits ***");
for (String split : splits) System.out.println(split);
输出:
*** Replacements ***
(TOP~did~1~1 (S~did~2~2 (NPB~I~1~1 ISupermanPRP ) (VP~did~3~1 didSupermanVBD notSupermanRB (VP~read~2~1 readSupermanVB (NPB~article~2~2 theSupermanDT articleSupermanNN .SupermanPUNC. ) ) ) ) )
(TOP SourceSupermanNN http://www.alwatan.com.sa/daily/2007-01-31/first_page/first_page01.htmSupermanX .Superman. )
(NPB~sister~2~2 YourSupermanPRP$ sisterSupermanNN /SupermanPUNC: )
*** Splits ***
(TOP~did~1~1 (S~did~2~2 (NPB~I~1~1 I
PRP ) (VP~did~3~1 did
VBD not
RB (VP~read~2~1 read
VB (NPB~article~2~2 the
DT article
NN .
PUNC. ) ) ) ) )
(TOP Source
NN http://www.alwatan.com.sa/daily/2007-01-31/first_page/first_page01.htm
X .
. )
(NPB~sister~2~2 Your
PRP$ sister
NN /
PUNC: )
§
而不是/
可能更容易/更易于维护。 - collapsar