0

I have a Question in regex Expressions.

I want to make nested same values into a single group.

But,I was trying to using regular expression i won't work.

Example String:

<one listtype="NumberList1">one</one>
<one listtype="NumberList1">one</one>
<one listtype="NumberList1">one</one>

I want to get the three <one></one> tag as a single group.

How can I do this??

My regex pattern is:

Pattern pattern = Pattern.compile("(<one (.*?)>(.*?)</one>)+");
    Matcher matcher = pattern.matcher(val);
    while (matcher.find()) {
        System.out.println("group 1: " + matcher.group(1));
        }

My result is:

 group 1:<one listtype="NumberList1">one</one>
 group 1:<one listtype="NumberList1">one</one>
 group 1:<one listtype="NumberList1">one</one>

I want:

group 1:<one listtype="NumberList1">one</one><one listtype="NumberList1">one</one><one listtype="NumberList1">one</one>

I want to make this as a single group.

How can i do this?

1 Answer 1

1

If you want to match three such <one> tags in succession, then just use an appropriate pattern:

Pattern pattern = Pattern.compile("((?:<one (?:.*?)>(?:.*?)</one>\\s*){3})");
Matcher matcher = pattern.matcher(val);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
}

Demo here:

Rextester

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

9 Comments

Sorry, the regex I was using had a slight problem, it appears to be working now.
Thanks bro.But,just in case it is more then 3 how can i capture bro.
Just change {3} to the number you want or use * for any number.
I'm trying this ((?:<one (?:.*?)>(?:.*?)</one>\\s*){*}) bro.But, It's given an Error like this Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 33 ((?:<one (?:.*?)>(?:.*?)</one>\s*){*})
I have answered your question. Don't bro me if you don't know me.
|

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.