Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Match Non-Whitespace Characters

I need to make a regular expression that matches something like:

JG2144-141/hello

or

!

but not:

laptop bag

or a string consisting of whitespace chars only (' ').

Right now I have [A-Za-z0-9-!/\S], but it isn't working because it still matches with laptop and bag individually. It shouldn't match laptop bag and the empty string at all.

like image 313
Jennifer Hall Avatar asked Nov 19 '17 21:11

Jennifer Hall


People also ask

What is a non-whitespace character in regex?

Whitespace character: \s. Non-whitespace character: \S.

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.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Which modifier ignores white space in regex?

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.


1 Answers

In general, to match any non-whitespace char, you can use

\S              # Common modern regex flavors
[^[:space:]]    # POSIX compliant
[[:^space:]]    # POSIX extension (available in some flavors)
%S              # Lua patterns

The \S in [A-Za-z0-9-!/\S] makes this character class equal to \S, but you want to make sure all chars in the string are non-whitespace chars. That is why you should wrap the pattern with ^ and $ anchors and add a + quantifier after \S to match 1 or more occurrences of this subpattern.

You may use

^\S+$

See the regex demo

Details

  • ^ - start of string
  • \S+ - 1 or more non-whitespace chars
  • $ - end of string.
like image 111
Wiktor Stribiżew Avatar answered Sep 18 '22 23:09

Wiktor Stribiżew