[英]REGEX How can I check if a string has more than 2 spaces in it?
I am trying to regex (ECMAscript) check if a string has three or more spaces in it.我正在尝试使用正则表达式 (ECMAscript) 检查字符串中是否包含三个或更多空格。 Essentially, I want the minimum number of spaces to be 3 before it matches.本质上,我希望在匹配之前的最小空格数为 3。 Here are some examples;这里有些例子;
"Microsoft and Apple" This would NOT match “微软和苹果”这不匹配
"The quick brown fox" This WOULD match “The quick brown fox”这会匹配
"lots of spaces in this sentence" This WOULD match “这句话中有很多空格”这将匹配
This is the best I have so far;这是我迄今为止最好的;
/[\s]{3,}/gm /[\s]{3,}/gm
If the 'string' can contain everything (characters and numbers and special chars):如果“字符串”可以包含所有内容(字符和数字以及特殊字符):
/^((.*?)? (.*?)?){3,}?$/gm
This may not be optimally efficient, but you could split
on spaces and then check the resulting length:这可能不是最有效的,但您可以按空格split
,然后检查结果长度:
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))
Put three spaces in the regex, and match anything else around them在正则表达式中放置三个空格,并匹配它们周围的任何其他内容
.*.*.*.*
A regex that makes sure there at least 3 whitespaces in a string is确保字符串中至少有 3 个空格的正则表达式是
/^(?:\S*\s){3}/
See the regex demo .请参阅正则表达式演示。 Details :详情:
^
- start of string ^
- 字符串的开始(?:\S*\s){3}
- three occurrences of zero or more non-whitespace chars and then a whitespace. (?:\S*\s){3}
- 零个或多个非空白字符出现三次,然后是一个空白。See the JavaScript demo:请参阅 JavaScript 演示:
const texts = ['Microsoft and Apple','The quick brown fox','lots of spaces in this sentence']; const re = /^(?:\S*\s){3}/; for (const text of texts) { console.log(text, '=>', re.test(text)); }
The pattern /[\s]{3,}/gm
matches 3 continuous whitespace characters, and \s
can also match newlines.模式/[\s]{3,}/gm
匹配 3 个连续的空白字符, \s
也可以匹配换行符。
Note that you don't need /m
as the pattern has no anchors, but you do need /g
to get all matches.请注意,您不需要/m
因为该模式没有锚点,但您确实需要/g
才能获得所有匹配项。
You can match all spaces您可以匹配所有空格
and only get the string that has more than 2 spaces (or if you really want to use \s
then use that)并且只获取超过 2 个空格的字符串(或者如果你真的想使用\s
然后使用它)
[ "Microsoft and Apple", "The quick brown fox", "lots of spaces in this sentence" ].forEach(s => { if ((s.match(/ /g) || []).length > 2) { console.log(s); } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.