简体   繁体   中英

How do I split this String using regex in Java?

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!

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)

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));

You can use split method in chain.

 String test = "/resources/pages/id/AirOceanFreight.xhtml";
 String result = test.split(".xhtml")[0].split("/resources/pages/")[1];

You can also try with the following regular expression pattern:

(?<=pages\\/)(.+(?=.xhtml))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM