Ilya Chernomordik
Ilya Chernomordik

Reputation: 30195

A regex for letters and space that cannot be a whitespace

I cannot figure out how to add two regex together, I have these requirements:

  1. Letters and space ^[\p{L} ]+$
  2. Cannot be whitespace ^[^\s]+$

I cannot figure out how to write one regex that will combine both? There is perhaps some other solution?

Upvotes: 1

Views: 28

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use

^(?! +$)[\p{L} ]+$
^(?!\s+$)[\p{L}\s]+$
^\s*\p{L}[\p{L}\s]*$

Details

  • ^ - start of string
  • (?!\s+$) - no 1 or more whitespaces are allowed till the end of the string
  • [\p{L}\s]+ - 1+ letters or whitespaces
  • $ - end of string.

See the regex demo.

The ^\s*\p{L}[\p{L}\s]*$ is a regex that matches any 0+ whitespaces at the start of the string, then requires a letter that it consumes, and then any 0+ letters/whitespaces may follow.

See the regex demo.

Upvotes: 1

Related Questions