Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that matches anything except for all whitespace

I need a (javascript compliant) regex that will match any string except a string that contains only whitespace. Cases:

" "         (one space) => doesn't match
"    "      (multiple adjacent spaces) => doesn't match
"foo"       (no whitespace) => matches
"foo bar"   (whitespace between non-whitespace) => matches
"foo  "     (trailing whitespace) => matches
"  foo"     (leading whitespace) => matches
"  foo   "  (leading and trailing whitespace) => matches
like image 993
Bill Dami Avatar asked Jan 20 '12 21:01

Bill Dami


People also ask

Is used for matches any non whitespace characters?

The \S metacharacter matches non-whitespace characters. Whitespace characters can be: A space character.

Which modifier ignores white space in regex?

Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments. Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments, both inside and outside character classes.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do I get rid of white space in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.


1 Answers

This looks for at least one non whitespace character.

/\S/.test("   ");      // false
/\S/.test(" ");        // false
/\S/.test("");         // false


/\S/.test("foo");      // true
/\S/.test("foo bar");  // true
/\S/.test("foo  ");    // true
/\S/.test("  foo");    // true
/\S/.test("  foo   "); // true

I guess I'm assuming that an empty string should be consider whitespace only.

If an empty string (which technically doesn't contain all whitespace, because it contains nothing) should pass the test, then change it to...

/\S|^$/.test("  ");      // false

/\S|^$/.test("");        // true
/\S|^$/.test("  foo  "); // true
like image 65
2 revsuser1106925 Avatar answered Sep 18 '22 19:09

2 revsuser1106925