James
James

Reputation: 11

How to Regex replace characters at the end of a string

I have an issue in Java when trying to remove the characters from the end of a string. This has now become a generic pattern match issue that I cannot resolve.

PROBLEM = remove all pluses, minuses and spaces (not bothered about whitespace) from the end of a string.

Pattern myRegex;
Matcher myMatch;
String myPattern = "";
String myString = "";
String myResult = "";

myString="surname; forename--+  + --++   "
myPattern="^(.*)[-+ ]*$"
//expected result = "surname; forename"
myRegex = Pattern.compile(myPattern);
myMatch = myRegex.matcher(myString);

if (myMatch.find( )) {
    myResult = myMatch.group(1);
} else {
    myResult = myString;
}

The only way I can get this to work is by reversing the string and reversing the pattern match, then I reverse the result to get the right answer!

Upvotes: 0

Views: 4079

Answers (1)

Jason
Jason

Reputation: 11832

In the following pattern:

^(.*)[-+ ]*$

... the .* is a greedy match. This means that it will match as many characters as possible while still allowing the entire pattern to match.

You need to change it to non-greedy by adding ?.

^(.*?)[-+ ]*$

Upvotes: 1

Related Questions