Reputation: 73
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);
}
}
Upvotes: 0
Views: 38
Reputation: 520928
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);
Upvotes: 1