3

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!

4 Answers 4

9

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)

Sign up to request clarification or add additional context in comments.

3 Comments

and then String res[] = x.split('/');
wow that is fast. and looks so much simpler than java.util.regex. thanks!
Being simpler to use than the Java SDK is the main point of Commons Lang. You do need that extra jar file though (but it is well worth it, lots of nice *Utils). Another option is Google's Guava library.
3

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

Comments

1

You can use split method in chain.

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

Comments

0

You can also try with the following regular expression pattern:

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

1 Comment

I think you must escape dot before "xhtml"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.