Home > other >  REGEX How can I check if a string has more than 2 spaces in it?
REGEX How can I check if a string has more than 2 spaces in it?

Time:02-20

I am trying to regex (ECMAscript) check if a string has three or more spaces in it. Essentially, I want the minimum number of spaces to be 3 before it matches. Here are some examples;

"Microsoft and Apple" This would NOT match

"The quick brown fox" This WOULD match

"lots of spaces in this sentence" This WOULD match

This is the best I have so far;


/[\s]{3,}/gm


CodePudding user response:

If the 'string' can contain everything (characters and numbers and special chars):

/^((.*?)? (.*?)?){3,}?$/gm

CodePudding user response:

This may not be optimally efficient, but you could split on spaces and then check the resulting length:

const x = [
 "Microsoft and Apple",
 "The quick brown fox",
 "lots of spaces in this sentence",
]

x.forEach(s => console.log(s, s.split(' ').length > 3))

CodePudding user response:

Put three spaces in the regex, and match anything else around them

.* .* .* .*

  • Related