1

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

1
  • use string.lastIndexOf('$') Commented Apr 29, 2014 at 16:32

4 Answers 4

1

Try this:

String name = qualified.replaceAll(".+?\\W", "");

.*\\W matches everything before $ or . and replaces it with empty string.

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

2 Comments

For a input string "com.domain.app.RootEntity" it returns empty, it should return RootEntity
@xybrek, glad to have helped.
1

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

Comments

0

Simple:

String resultString = qualified.replaceAll("(?m).*?(RootEntity)$", "$1");

Comments

0
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

Comments

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.