Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Matches white space but not tab (php)

How to write a regex with matches whitespace but no tabs and new line? thanks everything

[[:blank:]]{2,} <-- Even though this isn't good for me because its whitespace or tab but not newlines.

like image 620
János Sági Avatar asked Nov 23 '17 17:11

János Sági


People also ask

Is tab a whitespace for regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

How do you match a tab in regex?

Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A).

How do you use whitespace in regex?

\s\d matches a whitespace character followed by a digit. [\s\d] matches a single character that is either whitespace or a digit. When applied to 1 + 2 = 3, the former regex matches 2 (space two), while the latter matches 1 (one).

What is used to match anything except a whitespace?

[^ ] matches anything but a space character.


2 Answers

As per my original comment, you can use this.

Code

See regex in use here

Note: The link contains whitespace characters: tab, newline, and space. Only space is matched.

[^\S\t\n\r]

So your regex would be [^\S\t\n\r]{2,}


Explanation

  • [^\S\t\n\r] Match any character not present in the set.
    • \S Matches any non-whitespace character. Since it's a double negative it will actually match any whitespace character. Adding \t, \n, and \r to the negated set ensures we exclude those specific characters as well. Basically, this regex is saying:
      • Match any whitespace character except \t\n\r

This principle in regex is often used with word characters \w to negate the underscore _ character: [^\W_]

like image 121
ctwheels Avatar answered Nov 03 '22 00:11

ctwheels


[ ]{2,} works normally (not sure about php) or even / {2,}/

like image 43
Johan Avatar answered Nov 03 '22 01:11

Johan