Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get String after a certain character using pattern matching?

Tags:

java

regex

String tect = "A to B";
Pattern ptrn = Pattern.compile("\\b(A.*)\\b");
Matcher mtchr = ptrn.matcher(tr.text()); 
while(mtchr.find()) {
    System.out.println( mtchr.group(1) );
}

I am getting output A to B but I want to B.

Please help me.

like image 360
user3064366 Avatar asked Oct 03 '22 05:10

user3064366


1 Answers

You can just place the A outside of your capturing group.

String s  = "A to B";
Pattern p = Pattern.compile("A *(.*)");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group(1)); // "to B"
}

You could also split the string.

String s = "A to B";
String[] parts = s.split("A *");
System.out.println(parts[1]); // "to B"
like image 193
hwnd Avatar answered Oct 13 '22 10:10

hwnd