2

For instance i'm trying to search this string

"this is a search LLC which can end up having spaces"

using the below regex, it's working fine but when I match and then remove it's causes a bunch of white spaces, so I want to limit the number the white space to just 1, how could I go about adding that?

(?i)(?<=|^)LLC|end|having(?=|$)

this is a search LLC which can end up having spaces

this is a search which can up spaces

public static String removeValuesByRegex(String input, Pattern pattern, String replaceWith){
    String result;

    Matcher matcher = pattern.matcher(input);

    return result = matcher.replaceAll(replaceWith).trim();
}

Then in my test class im doing

String keywords = 'LLC|end|Having';
Pattern pattern = Pattern.compile('(?i)(?<= |^)\'|' + keyWords + '\'|(?= |$)');

String stringResult = UtilString.removeValuesByRegex('This is a LLC and General Partnership Test ', pattern, '');
4

If you want to remove duplicate spacing, I recommend you call normalizeSpace on the output:

String result = MyClass.myMethod(input, pattern, '').normalizeSpace();

Note from the documentation:

normalizeSpace()
Returns the current String with leading, trailing, and repeating white space characters removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.