-1

Can I write a single line regular expression instead of the five lines below?

strTestIn = strTestIn.replaceAll("^\\s+", "");
strTestIn = strTestIn.replaceAll("[ ]+", " ");
strTestIn = strTestIn.replaceAll("(\\r\\n)+", "\r\n");
strTestIn = strTestIn.replaceAll("(\\t)+", " ");
strTestIn = strTestIn.replaceAll("\\s+$", "");

What's the difference between these regular expressions?

6
  • 1
    if would be helpful if you explained what you are trying to achieve - what this code is really trying to do
    – mvp
    Commented Jun 11, 2013 at 9:18
  • 1
    See Pattern...
    – devconsole
    Commented Jun 11, 2013 at 9:18
  • 2
    Why the downvotes? It's a clear question where the OP doesn't know the answer. That's what SO is for. Commented Jun 11, 2013 at 9:20
  • See my answer. You need only two lines and one regex only!
    – fge
    Commented Jun 11, 2013 at 9:22
  • 1
    and now a "close" vote as "too localized". It's not; it's a widely applicable request. (It might be a duplicate, but that's another matter) Commented Jun 11, 2013 at 9:29

1 Answer 1

6
strTestIn = strTestIn.replaceAll("^\\s+", "");

removes whitespace at the start of the string.

strTestIn = strTestIn.replaceAll("\\s+$", "");

removes whitespace at the end of the string.

strTestIn = strTestIn.replaceAll("[ ]+", " ");

condenses multiple spaces into a single space.

strTestIn =strTestIn.replaceAll("(\\r\\n)+", "\r\n");

removes empty lines by replacing adjacent newlines with a single newline.

strTestIn = strTestIn.replaceAll("(\\t)+", " ");

condenses tabs into a single space.

So they all do different things. A combination is possible for those that have the same replacement string:

strTestIn = strTestIn.replaceAll("^\\s+|\\s+$", "");
strTestIn = strTestIn.replaceAll(" {2,}|\t+", " ");
strTestIn = strTestIn.replaceAll("(\r\n)+", "\r\n");

You can also clean up and improve the regexes a bit (removing some unnecessary backslashes, and changing the minimum number of spaces to two).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.