Find all words between <and> using Regex

I want to find a word between <and >from a string.

For instance:

String str=your mobile number is <A> and username is <B> thanks <C>;

I want to get A, B, Cfrom a string.

I tried

import java.util.regex.*;

public class Main
{
  public static void main (String[] args)
  {
     String example = your mobile number is <A> and username is <B> thanks <C>;
     Matcher m = Pattern.compile("\\<([^)]+)\\>").matcher(example);
     while(m.find()) {
       System.out.println(m.group(1));    
     }
  }
}

What happened to what I'm doing?

+4
source share
3 answers

Use the following idiom and link back to get value for your A, Band Caggregates:

String example = "your mobile number is <A> and username is <B> thanks <C>";
//                           ┌ left delimiter - no need to escape here
//                           | ┌ group 1: 1+ of any character, reluctantly quantified
//                           | |   ┌ right delimiter
//                           | |   |
Matcher m = Pattern.compile("<(.+?)>").matcher(example);
while (m.find()) {
    System.out.println(m.group(1));
}

Output

A
B
C

Note

If you prefer a solution without indexed backlinks and “look-arounds”, you can achieve the same with the following code:

String example = "your mobile number is <A> and username is <B> thanks <C>";
//                            ┌ positive look-behind for left delimiter
//                            |    ┌ 1+ of any character, reluctantly quantified
//                            |    |   ┌ positive look-ahead for right delimiter
//                            |    |   |
Matcher m = Pattern.compile("(?<=<).+?(?=>)").matcher(example);
while (m.find()) {
    // no index for back-reference here, catching main group
    System.out.println(m.group());
}

I personally find the latter less readable in this case.

+6
source

> <> . [^)]+ charcater, ), . , < >.

 Matcher m = Pattern.compile("<([^<>]+)>").matcher(example);
 while(m.find()) {
   System.out.println(m.group(1));
 }

.

 Matcher m = Pattern.compile("(?<=<)[^<>]*(?=>)").matcher(example);
 while(m.find()) {
   System.out.println(m.group());
 }
+1

Can you try this?

public static void main(String[] args) {
        String example = "your mobile number is <A> and username is <B> thanks <C>";
        Matcher m = Pattern.compile("\\<(.+?)\\>").matcher(example);
        while(m.find()) {
            System.out.println(m.group(1));
        }
    }
+1
source

All Articles