javascript - RegEx 用于检查另一个字符之后的字符 X 位置
问题描述
我已经完成了一个非常基本的步骤,它检查是否存在一个特殊字符。下一步需要一些建议,因为我希望能够在找到 # 后从 1 个位置开始搜索另一个特殊字符。
var reg = /#/;
alert(reg.test(string))
例如:
abc#.123 //invalid - as . is immediately after #
abc#12.3 //valid - as . is more than 1 character after #
abc#abcd.23 //valid - as . is more than 1 character after #
a#123.12 //valid - as . is more than 1 character after #
a#12123124.12 //valid - as . is more than 1 character after #
abcd#1231.09 //valid - as . is more than 1 character after #
1.23#12312.01 //invalid - as . is before #
123#122.01#12 //invalid - as there is another# after .
#
因此, and之间的差距.
应该始终是 1 个或多个字符,并且#
始终排在第一位。
解决方案
您可以使用/^[^\.#]*#[^\.#]+\.[^\.#]*$/
.
^ beginning of line anchor
[^\.#]* zero or more characters other than . and #
# literal # character
[^\.#]+ one or more characters other than . and #
\. literal . character
[^\.#]* one or more characters other than . and #
$ EOL
通常,/^[^\.#]*#[^\.#]{5,}\.[^#\.]*$/
如果您想要一个特定大小的最小间隙(在本例中为 5 或更大),或者{5}
您希望间隙正好为 5,请使用。
var reg = /^[^\.#]*#[^\.#]+\.[^\.#]*$/;
[
"abc#.123", // invalid - as . is immediately after #
"abc#12.3", // valid - as . is more than 1 character after #
"abc#abcd.23", // valid - as . is more than 1 character after #
"a#123.12", // valid - as . is more than 1 character after #
"a#12123124.12", // valid - as . is more than 1 character after #
"abcd#1231.09", // valid - as . is more than 1 character after #
"1.23#12312.01", // invalid - as . is before #
"123#122.01#12", // invalid - as there is another# after .
].forEach(test => console.log(reg.test(test)));
推荐阅读
- javascript - 反应打字稿计数器不更新
- react-native - expo init 失败 React-native@https://github.com/expo/react-native/archive/sdk-33.0.0.tar.gz 似乎已损坏。再试一次
- server - 我的世界服务器 eula.txt 无法识别
- angular - Angular testbed - 测试通过父组件的输入传递的异步 observable
- sql-server - 脚本任务中未生成的变量
- powerbi - 如何将 COUNTIFS Excel 公式转换为 DAX 以获取汇总数据
- python - `python -m pytest`与virtualenv中的pytest?
- javascript - 如何让我的每个类属性显示随机颜色?
- javascript - 如何迭代一些数组并生成哈希
- symfony - 基于来自主域的会话变量,子域自动登录用户上的 Symfony 应用程序