Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split this String using regex in Java?

Tags:

java

regex

From this string: "/resources/pages/id/AirOceanFreight.xhtml"

I need to retrieve two sub-strings: the string after pages/ and the string before .xhtml.

/resources/pages/ is constant. id and AirOceanFreight varies.

Any help appreciated, thanks!

like image 452
el_zako Avatar asked Jun 14 '26 11:06

el_zako


2 Answers

I like Jakarta Commons Lang StringUtils:

String x = StringUtils.substringBetween(string, "/resources/pages/", ".xhtml");

Or, if ".xhtml" can also appear in the middle of the string:

String x = substringBeforeLast(
              substringAfter(string, "/resources/pages/"), ".xhtml");

(I also like static imports)

like image 165
Thilo Avatar answered Jun 16 '26 03:06

Thilo


An alternative without jakarta commons. Using the constants:

 private final static String PATH = "/resources/pages/";
 private final static String EXT = ".xhtml";

you'll just have to do:

 String result = filename.substring(PATH.length(), filename.lastIndexOf(EXT));
like image 40
Andreas Dolk Avatar answered Jun 16 '26 02:06

Andreas Dolk