Check if string contains only whitespace

Use the str.isspace() method: Return True if there are only whitespace characters in the string and there is at least one character, False otherwise. A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S. … Read more

How to remove duplicate white spaces in string using Java?

Like this: yourString = yourString.replaceAll(“\\s+”, ” “); For example System.out.println(“lorem ipsum dolor \n sit.”.replaceAll(“\\s+”, ” “)); outputs lorem ipsum dolor sit. What does that \s+ mean? \s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says “one or more of those”. Thus the … Read more

Make Git automatically remove trailing white space before committing

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to: core.whitespace: detect them, and raise errors apply.whitespace: and strip them, but only during patch, not “always automatically” I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace) Note that at any given time you … Read more

Whitespace Matching Regex – Java

You can’t use \s in Java to match white space on its own native character set, because Java doesn’t support the Unicode white space property — even though doing so is strictly required to meet UTS#18’s RL1.2! What it does have is not standards-conforming, alas. Unicode defines 26 code points as \p{White_Space}: 20 of them … Read more

Remove multiple whitespaces

You need: $ro = preg_replace(‘/\s+/’, ‘ ‘, $row[‘message’]); You are using \s\s+ which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space. What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s* … Read more

Split by comma and strip whitespace in Python

Use list comprehension — simpler, and just as easy to read as a for loop. my_string = “blah, lots , of , spaces, here ” result = [x.strip() for x in my_string.split(‘,’)] # result is [“blah”, “lots”, “of”, “spaces”, “here”] See: Python docs on List Comprehension A good 2 second explanation of list comprehension.