Adnan
Adnan

Reputation: 613

How can I match multiple sets of a regular expression pattern in the same string?

I am building a regex against strings that meet the following requirements:

  1. The string has a maximum of 5 sets of alphanumeric characters.
  2. Each set within the string is separated by SINGLE whitespace character.

For example, we can have "asa22d asdcac3" or "Asdcd234 sacasW2 sas1 s sd1" (hopefully you get the picture). So far I have:

^[A-z 0-9]\s{0,1}

I am not using \w because it allows underscores. This works for one set of characters, but I need to allow five sets of the same sort of strings separated by a space.

How can I do that?

Upvotes: 3

Views: 7946

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84363

Tools You Need

To match multiple instances of a pattern in a regular expression, you can use any combination of match groups, backreferences, and interval expressions allowed by your regular expression engine.

Examples

Based on your sample code, your regular expression engine clearly supports intervals, so use that. Here are two examples that will accomplish the goal.

# Use POSIX character classes with an interval expression
^([[:alnum:]]+[[:space:]]?){1,5}$

# PCRE expression with intervals
\A(\p{Xan}+\s?){1,5}\Z

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375604

You haven't said what language you are using, but this should do it for you:

^[A-Za-z0-9]+(\s[A-Za-z0-9]+){0,4}$

A word, followed by up to four instances of space-then-word.

Upvotes: 3

Related Questions