0

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 =?

Nico Laus
  • 1
  • 2

3 Answers3

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

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

Bjerrum
  • 108
  • 6
0

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.

Nanor
  • 2,400
  • 6
  • 35
  • 66
0

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*", "=");
Mr R
  • 754
  • 7
  • 19