Here is my code to match a String like:
String name = qualified.replaceAll(".*\\.(?=\\w+)", "");
Where it gets from input org.myapp.TestData$RootEntity
a TestData$RootEntity
However I need to be able to get just the RootEntity
part of the String. Effectively getting just this.
Input Strings:
com.domain.app.RootEntity
com.domain.app.TestData$RootEntity
com.domain.app.TestData$TestNested$RootEntity
And should be able to get RootEntity
Try this:
String name = qualified.replaceAll(".+?\\W", "");
.*\\\\W
matches everything before $
or .
and replaces it with empty string.
Try with simple String#lastIndexOf()
String qualified = "org.myapp.TestData$RootEntity";
String name = qualified.substring(qualified.lastIndexOf('$') + 1);
Complete code
String[] values = new String[] { "com.domain.app.RootEntity",
"com.domain.app.TestData$RootEntity",
"com.domain.app.TestData$TestNested$RootEntity" };
for (String qualified : values) {
int index = qualified.lastIndexOf('$');
String name = null;
if (index != -1) {
name = qualified.substring(qualified.lastIndexOf('$') + 1);
} else {
name = qualified.substring(qualified.lastIndexOf('.') + 1);
}
System.out.println(name);
}
output:
RootEntity
RootEntity
RootEntity
简单:
String resultString = qualified.replaceAll("(?m).*?(RootEntity)$", "$1");
com.domain.app.RootEntity
com.domain.app.TestData$RootEntity
com.domain.app.TestData$TestNested$RootEntity
And should be able to get
RootEntity
In looks like you want to remove each part of name which has .
or $
after it like app.
or TestData$
.
If that is the case you can try
replaceAll("\\w+[.$]", "")
Demo
String[] data = {
"com.domain.app.RootEntity",
"com.domain.app.TestData$RootEntity",
"com.domain.app.TestData$TestNested$RootEntity",
};
for (String s:data)
System.out.println(s.replaceAll("\\w+[.$]", ""));
Output:
RootEntity
RootEntity
RootEntity
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.