2

This is my input string and I wanted to break it up into 5 parts according to regex below so that I can print out the 5 groups but I always get a no match found. What am I doing wrong ?

String content="beit Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<m>Surface Transportation Extension Act of 2012.,<xm>";

Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE);
System.out.println(regEx.matcher(content).group(1));
System.out.println(regEx.matcher(content).group(2));
System.out.println(regEx.matcher(content).group(3));
System.out.println(regEx.matcher(content).group(4));
System.out.println(regEx.matcher(content).group(5));

2 Answers 2

0
Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE);
Matcher matcher = regEx.matcher(content);
if (matcher.find()) { // calling find() is important
// if the regex matches multiple times, use while instead of if
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
    System.out.println(matcher.group(4));
    System.out.println(matcher.group(5));
} else {
    System.out.println("Regex didn't match");
}
Sign up to request clarification or add additional context in comments.

3 Comments

jlordo, I ultimately want to do this: "regEx.matcher(content).replaceAll(replaceExpression)" and my replaceExpression is like: "$1<marginal>$3</marginal>$5" but it doesnt replace.
@Phoenix: and where's the problem? You didn't address that in your question at all.
@jlordo: he asked a first question here, but didn't have an answer for 50 minutes (gasp!), so he asked another.
0

Your regex's 5th match doesn't match anything - there is no content after the <xm>. Also, you should really run regEx.matcher() once, and then pull the groups out of the one matcher; as written, it executes the regex 5 times, once to get each group out. Also your RegEx is never executed unless you call find() or matches.

2 Comments

it actually executes the regex never, becaue neither find() nor matches() is ever called.
find() and matches() can't be called on a Pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.