javascript - Detect 2 spaces in whole string(sentence) with regex JS
问题描述
I need to detect if the sentence has more than ONE space: "one space" => false "two or more spaces inside" => true
I have such regex /\s\s+/g
but it doesn't seem correct as it detects two spaces in a row but not in the whole provided string. How can I find more then ONE space in WHOLE string?
解决方案
注意也\s
可以匹配换行符。
一个选项可以从字符串的开头匹配 2 次,尽可能少的字符,然后是一个没有换行符的空白字符。
^.*?[^\S\r\n].*?[^\S\r\n]
^
字符串的开始.*?
匹配尽可能少的字符[^\S\r\n]
使用否定字符类匹配没有换行符的空格[^
.*?
匹配尽可能少的字符[^\S\r\n]
匹配没有换行符的空格
[" a b", "a b ", " aa ", " b", " a", "b "]
.forEach(s => console.log(`"${s}" --> ${/^.*?[^\S\r\n].*?[^\S\r\n]/.test(s)}`))
例如,您还可以使用匹配所有空白字符\s
,然后检查匹配数是否大于 1。
[" a b", "a b ", " aa ", " b", " a", "b "]
.forEach(s => console.log(`"${s}" --> ${s.match(/\s/g).length > 1}`))
推荐阅读
- javascript - 盒子之塔(愤怒的小鸟)
- javascript - 如何在 Vuex 中使用动态键正确访问记录
- dask - Dask 与 Pyarrow 的兼容性并从 CSV 读取
- vue.js - Vue2/Router3 — 滚动行为不起作用
- drag-and-drop - Kotlin可组合detectDragGestures在放置位置输出?
- elasticsearch - 我们如何在 Java 代码中实现累积基数?
- javascript - 如果我单击按钮,有没有办法查看按高度计算的手风琴菜单?
- excel - 如何遍历范围对象VBA的每一行中的特定列?
- c# - 在 Unity c# 中,我无法使用 animation.SetInteger 让动画过渡
- reactjs - 如何修复 npm 漏洞?我尝试了两种方法,问题仍然存在