[英]How do I split this String using regex in Java?
From this string: "/resources/pages/id/AirOceanFreight.xhtml" 从这个字符串:“/ resourcesspages/id/AirOceanFreight.xhtml”
I need to retrieve two sub-strings: the string after pages/ and the string before .xhtml. 我需要检索两个子字符串:pages /之后的字符串和.xhtml之前的字符串。
/resources/pages/ is constant. / resources / pages /是不变的。 id and AirOceanFreight varies.
id和AirOceanFreight各不相同。
Any help appreciated, thanks! 任何帮助表示感谢,谢谢!
I like Jakarta Commons Lang StringUtils : 我喜欢Jakarta Commons Lang StringUtils :
String x = StringUtils.substringBetween(string, "/resources/pages/", ".xhtml");
Or, if ".xhtml"
can also appear in the middle of the string: 或者,如果
".xhtml"
也可以出现在字符串的中间:
String x = substringBeforeLast(
substringAfter(string, "/resources/pages/"), ".xhtml");
(I also like static imports) (我也喜欢静态导入)
An alternative without jakarta commons. 没有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)) (?<=页面\\ /)(。+(?=。XHTML))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.