Link: http://regexone.com/example/5
It asks: Write a simple regular expression to capture the content of each line, without the extra whitespace.
What I have is a mess with a bunch of \S+, is there an elegant way to solve this problem?
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
Trimming WhitespaceSearch for [ \t]+$ to trim trailing whitespace. Do both by combining the regular expressions into ^[ \t]+|[ \t]+$. Instead of [ \t] which matches a space or a tab, you can expand the character class into [ \t\r\n] if you also want to strip line breaks. Or you can use the shorthand \s instead.
Leading spaces (at the start of the text), Trailing spaces (at the end of the text) and Non-Breaking spaces (prevents line breaks from occurring at a particular point) usually get in the way when we want to perform operations in Excel.
The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning.
Writing regular expressions may seem like a black art, but it's actually quite simple; the most important step is to identify with surgical precision exactly what you do and do not want to match, then say just what you mean (no more and no less).
Another tip: when using *
or +
qualifiers, especially with "wildcard" characters like .
, always remember that part of the regex may "run past" the part which you wanted to match, perhaps matching the entire string. Often, the simplest solution is to use a reluctant qualifier like *?
or +?
instead. (The most common regexp bugs are those which make the regexp match when you didn't want it to or more than you wanted to.)
In this case, you want "the content of each line, without extra whitespace". That's not quite precise enough. What is "extra whitespace"? Trailing and leading whitespace? If so...
Let's express that in completely precise, non-ambiguous terms. What you basically have is:
Can you express that as a regex? Try doing so and posting it here, then I'll give you some feedback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With