Java正则表达式替换所有

Java正则表达式替换所有,java,regex,Java,Regex,我的文本将如下所示 | birth_date = {{birth date|1925|09|2|df=y}} | birth_place = [[Bristol]], [[England]], UK | death_date = {{death date and age|2000|11|16|1925|09|02|df=y}} | death_place = [[Eastbourne]], [[Sussex]], England

我的文本将如下所示

| birth_date          = {{birth date|1925|09|2|df=y}}
| birth_place         = [[Bristol]], [[England]], UK
| death_date          = {{death date and age|2000|11|16|1925|09|02|df=y}}
| death_place         = [[Eastbourne]], [[Sussex]], England, UK
| origin              = 
| instrument          = [[Piano]]
| genre               = 
| occupation          = [[Musician]]
我想获取[[]中的所有内容。我尝试使用replace all替换不在[[]]内的所有内容,然后使用split by new line获得包含[[]]的文本列表

input = input.replaceAll("^[\\[\\[(.+)\\]\\]]", "");
所需输出:

[[Bristol]]
[[England]]
[[Eastbourne]]
[[Sussex]]
[[Piano]]
[[Musician]]

但这并没有提供所需的输出。我错过了什么?。有成千上万的文档,这是获取文档的最快方式吗?如果没有,请告诉我获得所需输出的最佳方法。

您需要匹配它,而不是替换它

Matcher m=Pattern.compile("\\[\\[\\w+\\]\\]").matcher(input);
while(m.find())
{
    m.group();//result
}

你需要匹配它,而不是替换它

Matcher m=Pattern.compile("\\[\\[\\w+\\]\\]").matcher(input);
while(m.find())
{
    m.group();//result
}
使用。例如:

import java.util.regex.*;

...

String text =
    "| birth_date          = {{birth date|1925|09|2|df=y}}\n" +
    "| birth_place         = [[Bristol]], [[England]], UK\n" +
    "| death_date          = {{death date and age|2000|11|16|1925|09|02|df=y}}\n" +
    "| death_place         = [[Eastbourne]], [[Sussex]], England, UK\n" +
    "| origin              = \n" +
    "| instrument          = [[Piano]]\n" +
    "| genre               = \n" +
    "| occupation          = [[Musician]]\n";
Pattern pattern = Pattern.compile("\\[\\[.+?\\]\\]");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}
使用。例如:

import java.util.regex.*;

...

String text =
    "| birth_date          = {{birth date|1925|09|2|df=y}}\n" +
    "| birth_place         = [[Bristol]], [[England]], UK\n" +
    "| death_date          = {{death date and age|2000|11|16|1925|09|02|df=y}}\n" +
    "| death_place         = [[Eastbourne]], [[Sussex]], England, UK\n" +
    "| origin              = \n" +
    "| instrument          = [[Piano]]\n" +
    "| genre               = \n" +
    "| occupation          = [[Musician]]\n";
Pattern pattern = Pattern.compile("\\[\\[.+?\\]\\]");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    System.out.println(matcher.group());
}

只是为了好玩,使用
replaceAll

 String output = input.replaceAll("(?s)(\\]\\]|^).*?(\\[\\[|$)", "$1\n$2");

只是为了好玩,使用
replaceAll

 String output = input.replaceAll("(?s)(\\]\\]|^).*?(\\[\\[|$)", "$1\n$2");

除其他问题外,请注意,
(.+)
是一个“贪婪”的量词,它将在
[[
]
之间尽可能多地抓取字符,这意味着对于
出生地
你将得到
“布里斯托尔”],[[England]
作为匹配项之一。在
+
之后添加
,就像falsetru的回答一样,可以防止出现这种情况。除其他问题外,请注意,
(.+)
是一个“贪婪”量词,它会在
[[
]之间抓取尽可能多的字符
,这意味着对于
出生地
您将获得
“布里斯托尔]],[[England”
作为匹配项之一。在
+
之后添加
,就像falsetru的回答一样,可以防止出现这种情况。