0

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
}
1
  • Usw regex101 to debug such regexes Commented Jul 23, 2016 at 11:43

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape the pipe '|'

Like this:

Matcher m = Pattern.compile("^(.*)#\\|#(.*)$").matcher(input);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.