-2
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.";

I want extra string between two special characters like ||anystring||, but it is not working. I tried to use Pattern-Matcher of Java but it is not working - it returns an empty array.

I have tried to follow Java- Extract part of a string between two special characters.

Pattern pattern = Pattern.compile("||(.*?)||");
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Karuna Dande
  • 93
  • 1
  • 1
  • 10

2 Answers2

1

It happens because | character has a special meaning in Regex so you have to escape it using \ character. See the demo at Regex101.

Moreover, in Java, you have to escape this character with double backslash \\.

Pattern pattern = Pattern.compile("\\|\\|(.*?)\\|\\|");
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

You need escape |

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));
}

Result:

PrimarySchool
Country
SecondarySchoolFemale
SecondarySchoolMale
LiteracyFemale
LiteracyMale
xingbin
  • 27,410
  • 9
  • 53
  • 103