String stringToSearch = "About ||PrimarySchool|| % of children in ||Country|| attend primary school. ||SecondarySchoolFemale|| % of girls and ||SecondarySchoolMale|| % of boys finish secondary school. Literacy is ||LiteracyFemale|| % for females and ||LiteracyMale|| % for males.";
我希望在||anystring||
这两个特殊字符之间添加额外字符串,但它不起作用。我尝试使用Java的Pattern-Matcher,但它不起作用 - 它返回一个空数组。
我试图关注Java- Extract part of a string between two special characters。
Pattern pattern = Pattern.compile("||(.*?)||");
答案 0 :(得分:1)
这是因为|
字符在Regex中具有特殊含义,因此您必须使用\
字符来转义它。请参阅Regex101上的演示。
此外,在Java中,您必须使用双反斜杠\\
来转义此字符。
Pattern pattern = Pattern.compile("\\|\\|(.*?)\\|\\|");
答案 1 :(得分:1)
您需要转义|
String stringToSearch = "About ||PrimarySchool|| % of children in ||Country|| attend primary school. ||SecondarySchoolFemale|| % of girls and ||SecondarySchoolMale|| % of boys finish secondary school. Literacy is ||LiteracyFemale|| % for females and ||LiteracyMale|| % for males.";
Pattern pattern = Pattern.compile("\\|\\|([^|]*)\\|\\|");
Matcher matcher = pattern.matcher(stringToSearch);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
结果:
PrimarySchool
Country
SecondarySchoolFemale
SecondarySchoolMale
LiteracyFemale
LiteracyMale