Finding substring using regular exp
I have a string
abc.xyz.qweweer.cccc
This is actually going to be a Java package name.
I am trying to find out the last string using reg exp, in the above example cccc
is the last St开发者_开发技巧ring.
Basically I am trying to find out the class name from the package string.
How to find out through Java
Given a string pkg = "abc.xyz.qweweer.cccc"
you can solve it like this:
Using
indexOf
:int index = pkg.lastIndexOf('.'); String lastPart = index == -1 ? pkg : pkg.substring(index + 1);
Using regular expressions with
Matcher
:Matcher m = Pattern.compile("[^.]*$").matcher(pkg); String lastPart = m.find() ? m.group() : null;
Using
split
(variation of RMT's answer):String[] names = pkg.split("\\."); String lastPart = names[names.length - 1];
Why not just split on the "."
String[] names = packageName.split(".");
String className = names[names.length-1];
Do you really want to use regex? You could do a str.substring (str.lastIndexOf (".") + 1)
to get the classname.
Alt1 - Extract desired
String packageName = ...
Matcher m = Pattern.compile("[a-zA-Z]+$").matcher(packageName);
if (m.find()) {
m.group(); // your match
}
Alt2 - Remove undesired
You could also try the somewhat less verbose approach:
String result = packageName.replaceAll(".*\\.", "");
You can use Apache StringUtils substringAfterLast for this.
StringUtils.substringAfterLast("abc.xyz.qweweer.cccc", ".")
Regex is not required for this.
精彩评论