Ryan
Ryan

Reputation: 12133

regex to match a single character that is anything but a space

I need to match a single character that is anything but a space but I don't know how to do that with regex.

Upvotes: 252

Views: 271974

Answers (3)

svin83
svin83

Reputation: 259

I use either [^[:space:]] or [^ ] depending on the situation.

Upvotes: 0

Andrew Moore
Andrew Moore

Reputation: 95444

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Upvotes: 348

cletus
cletus

Reputation: 625377

  • \s matches any white-space character
  • \S matches any non-white-space character
  • You can match a space character with just the space character;
  • [^ ] matches anything but a space character.

Pick whichever is most appropriate.

Upvotes: 165

Related Questions