Nico Laus
Nico Laus

Reputation: 1

How can I remove whitespaces around the first occurrence of specific char?

How can I remove the whitespaces before and after a specific char? I want also to remove the whitespaces only around the first occurrence of the specific char. In the examples below, I want to remove the whitespaces before and after the first occurrence of =.

For example for those strings:

something =           is equal to   =   something
something      =      is equal to   =   something
something      =is equal to   =   something

I need to have this result:

something=is equal to   =   something

Is there any regular expression that I can use or should I check for the index of the first occurrence of the char =?

Upvotes: 0

Views: 250

Answers (3)

Mr R
Mr R

Reputation: 794

Yes - you can create a Regex that matches optional whitespace followed by your pattern followed by optional whitepace, and then replace the first instance.

public static String replaceFirst(final String toMatch, final String forIP) {
    // string you want to match before and after
    final String quoted = Pattern.quote(toMatch);
    final Pattern patt = Pattern.compile("\\s*" + quoted + "\\s*");
    final Matcher match = patt.matcher(forIP);
    return match.replaceFirst(toMatch);
}

For your inputs this gives the expected result - assuming toMatch is =. It also works with arbitrary bigger things - eg.. imagine giving "is equal to" instead ... getting

something =is equal to=   something

For the simple case you can ignore the quoting, for an arbitrary case it helps (although as many contributors have pointed out before the Pattern.quoting isn't good for every case).

The simple case thus becomes

return forIP.replaceFirst("\\s*" + forIP + "\\s*", forIP);

OR

return forIP.replaceFirst("\\s*=\\s*", "=");

Upvotes: 0

Bjerrum
Bjerrum

Reputation: 108

private String removeLeadingAndTrailingWhitespaceOfFirstEqualsSign(String s1) {
    return s1.replaceFirst("\\s*=\\s*", "=");
}

Notice this matches all whitespace including tabs and new lines, not just space.

Upvotes: 1

Nanor
Nanor

Reputation: 2550

You can use the regular expression \w*\s*=\s* to get all matches. From there call trim on the first index in the array of matches.

Regex demo.

Upvotes: 0

Related Questions