RGoyal RGoyal - 27 days ago 10
Java Question

JAVA Regular expression to extract string after special characters

I need to extract string after the first three dots (example yyyy in following pattern):

xxx.xxx.xxxx.yyyy

here x could be anything (no,letters or )
yyyy can be letter or nos or abc. or abc


On using java pattern "
^.*\\.([^.]+)$
" , it works fine for string ab.bc.de.ef :
Code:

static final String REC_PATTERN = "^.*\\.([^.]+)$";
Pattern pattern = Pattern.compile(REC_PATTERN);
Matcher m = pattern.matcher("ab.bc.de.ef");
System.out.println(m.group(1)) //out put ef.


but it fails for
ab.bc.cd.de.11111
, I require output as de.1111 instead of 1111.
Could someone please help with relevant regular expression?

Answer Source

You may try this pattern : ^(?:\w+\.){3}(.*)$, as String : "^(?:\\w+\\.){3}(.*)$"

It finds the 3 dots with its text before, and capture what is next

And you may have forget m.find(), without that it doe not work