Fábio Silva
Fábio Silva

Reputation: 139

Regex to accept one or two words

I need a RegEx to match the following condition:

Examples of accepted strings:

Examples of non accepted string:

What I tried:

Upvotes: 0

Views: 2271

Answers (3)

Travis
Travis

Reputation: 2188

Here you go:

(?=^.{3,50}$)(\s*\p{L}+\s*){1,2}

Or if you don't want any leading whitespace, trailing whitespace, or more than one space between the words:

(?=^.{3,50}$)\p{L}+(\s\p{L}+)?

EDIT:

As this other SO post shows, Javascript has a problem with Unicode character classes. So, \p{L} won't work in Javascript.

What does that mean for you? Well, that other post shows three different solutions. Which solution is right for you depends on whether or not you know in advance exactly which accented characters or non-word (e.g. punctuation) characters might entered.

One possible approach is to list out the valid accented characters then concatenate it in to the regex:

var validWordCharacters = "[" + "a-z" + "A-Z" + "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ" + "]";

var regex = "(?=^.{3,50}$)" + validWordCharacters + "+(\s" + validWordCharacters + "+)?";

regexCompiled = new RegExp(regex);

Another possible (and more concise) solution is to use a range of code points:

var validWordCharacters = "[" + "a-z" + "A-Z" + "\u00C0-\u024F" + "]";

var regex = "(?=^.{3,50}$)" + validWordCharacters + "+(\s" + validWordCharacters + "+)?";

regexCompiled = new RegExp(regex);

Upvotes: 1

SamWhan
SamWhan

Reputation: 8332

You failed to tag what regex flavor/programming language/tool. But here's one way of doing it:

^(?=.{3,50}$)\p{L}*(\s\p{L}*)?$

It uses a positive look-ahead to make sure it's between 3 and 50 characters. Follwing that it simple checks for unicode letter class characters, optionally followed by a space and more letters, i.e. one or two words.

See it here at regex101.

Edit

OK - so for javascript you could try

^(?=.{3,50}$)[^\s\d]*(\s[^\s\d]*)?$

It's basically the same, only instead of matching the unicode class, it matches non space and digits. That's not perfect, but a simple solution that'll work in most (latin) cases.

See this here at regex101.

Upvotes: 1

Michael Piankov
Michael Piankov

Reputation: 1997

I think you may use next. It check minimum length but not check maximum. You may ensure it in different check

^([A-Za-z]{3,50}|([A-Za-z]+\s[A-Za-z]+))$

Upvotes: 0

Related Questions