Noel
Noel

Reputation: 11

How to allow spaces in between words?

EDIT: I've been experimenting, and it seems like putting this:

\(\w{1,12}\s*\)$

works, however, it only allows space at the end of the word.

example,

Matches

(stuff )
(stuff    )

Does not

(st uff)

Regexp:

\(\w{1,12}\)

This matches the following:

(stuff)

But not:

(stu ff)

I want to be able to match spaces too.

I've tried putting \s but it just broke the whole thing, nothing would match. I saw one post on here that said to enclose the whole thing in a ^[]*$ with space in there. That only made the regex match everything.

This is for Google Forms validation if that helps. I'm completely new to regex, so go easy on me. I looked up my problem but could not find anything that worked with my regex. (Is it because of the parenthesis?)

Upvotes: 1

Views: 183

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114230

If you are trying to get 12 characters between parentheses:

\([^\)]{1,12}\)

The [^\)] segment is a character class that represents all characters that aren't closing parentheses (^ inverts the class).

If you want some specific characters, like alphanumeric and spaces, group that into the character class instead:

\([\w ]{1,12}\)

Or

\([\w\s]{1,12}\)

If you want 12 word characters with an arbitrary number of spaces anywhere in between:

\(\s*(?:\w\s*){1,12}\)

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

For matching text like (st uff) or (st uff some more) you will need to write your regex like this,

\(\w{1,12}(?:\s+\w{1,12})*\)

Regex explanation:

  • \( - Literal start parenthesis
  • \w{1,12} - Match a word of length 1 to 12 like you wanted
  • (?:\s+\w{1,12})* - You need this pattern so it can match one or more space followed by a word of length 1 to 12 and whole of this pattern to repeat zero or more times
  • \) - Literal closing parenthesis

Demo

Now if you want to optionally also allow spaces just after starting parenthesis and ending parenthesis, you can just place \s* in the regex like this,

\(\s*\w{1,12}(?:\s+\w{1,12})*\s*\)
  ^^^                        ^^^

Demo with optional spaces

Upvotes: 1

Related Questions