我有一个字符串
String s="[[Identity (philosophy)|unique identity]]";
我需要将其解析为 .
s1 = Identity_philosphy
s2= unique identity
我尝试过以下代码
Pattern p = Pattern.compile("(\[\[)(\w*?\s\(\w*?\))(\s*[|])\w*(\]\])");
Matcher m = p.matcher(s);
while(m.find())
{
....
}
但是模式不匹配。
请帮忙
谢谢
使用
String s="[[Identity (philosophy)|unique identity]]";
String[] results = s.replaceAll("^\Q[[\E|]]$", "") // Delete double brackets at start/end
.replaceAll("\s+\(([^()]*)\)","_$1") // Replace spaces and parens with _
.split("\Q|\E"); // Split with pipe
System.out.println(results[0]);
System.out.println(results[1]);
输出:
Identity_philosophy
unique identity
String s="[[Identity (philosophy)|unique identity]]";
Matcher m = Pattern.compile("\[{2}(.*)\|(.*)]]").matcher(s);
if (m.matches()) {
System.out.println(m.group(1).replaceAll("\W+", " ").trim().replace(" ", "_")); // // => Identity_philosphy
System.out.println(m.group(2).trim()); // => unique identity
}
查看 Java 演示。
详
带有 matches()
的"\[{2}(.*)\|(.*)]]"
被解析为一种^[{2}(.*)|(.*)]]z
模式,该模式匹配以 [[
开头的字符串,然后将除换行符字符以外的任何 0 个或多个字符尽可能多地匹配并捕获到组 1 中,然后匹配一个|
,然后匹配并捕获除换行符字符以外的任何 0 个或多个字符到组中 2 中,然后匹配]]
。请参阅正则表达式演示。
2 中的内容可以从空格中修剪并按原样使用,但组 1 应通过用空格 ( .replaceAll("\W+", " ")
替换所有 1+ 非单词字符 chhunks 进行预处理,然后修剪结果 ( .trim()
) 并用 _
( .replace(" ", "_")
) 替换所有空格作为最后的润色。