Andy Band Andy Band - 4 months ago 22
Java Question

Extract string after particular pattern

I lost my head after trying to understand the way to extract the string after a particular pattern in one string.

the pattern is #|# and the string for example is:
Scirocco_#01_#|#Cp1freezer
I would like to find the pattern and extract the string after the end of pattern:
Cp1freezer

I have tried with regex expression ^(.)#|#(.)$ but I don't find the way out.

String input = "Scirocco_#01#|#Cp1";
Matcher m = Pattern.compile("^(.*)#|#(.*)$").matcher(input);
if(m.find()) {
String first = m.group(1); // Scirocco_#01
String second = m.group(2); // Cp1
}

Answer

First, you need to escape the | to match it literally. Second, you don't need to capture what precedes #|# if you only wish to extract what follows the #|#, so can remove the beginning of your expression. The first capture group will contains the desired substring:

"#\\|#(.*)$"

Demo: https://ideone.com/msXR3U

Comments