0
String str = "FirstName LastName - 1234xx"

In above case, want to replace above string with everything after " - " substring. In the above example it would mean changing str to 1234xx

The length of string after " - " is not fixed, hence cannot just capture last certain no. of characters

This approach gives FirstName LastName - - instead of desired output 1234xx

public class StringExample 
{
    public static void main(String[] args) 
    {
        String str = "FirstName LastName - 1234xx";
        String newStr = str.replaceAll("(?<=( - )).*", "$1");

        System.out.println(newStr);
    }
}
1
  • 1
    Could you provide more cases? It seems substring after '-' and trimmed all spaces is okay. Commented May 27, 2020 at 5:57

1 Answer 1

1

You were on the right track. Just use a lazy dot to consume everything up to and including the dash.

String str = "FirstName LastName - 1234xx";
String newStr = str.replaceAll("^.*-\\s*", "");

System.out.println(newStr);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, one thing though. Want everything after " - " and not "-". How to include whitespaces before and after "-"? Want this test case to fail FirstName LastName-1234xx
Not want that case to work. Based on your answer, think this would be the right implementation "^.*( - )\\s*", "". Can you verify?
instead of desired output 1234xx ... what is your desired output if not 1234xx ?
My sub-string to check would be " - " and not "-". Want those white-spaces around dash, then split substring beyound that. Input FirstName LastName - 1234xx should yeild 1234xx while FirstName LastName-1234xx should yield same string FirstName LastName-1234xx.Could reach to my desired answer though. Thanks

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.