RegEx 用于检查字符 X 在另一个字符之后的位置

RegEx for checking character X places after another character

我已经完成了一个非常基本的步骤,检查是否存在一个特殊字符。下一步需要一些建议,因为我希望能够在找到 # 后从 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 .

因此 #. 之间的间隔应始终为 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

一般来说,如果您想要 specifically-sized 最小间隙(在本例中为 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)));

您可以断言字符串 ^ 的开头,使用 negated character class [^#.] 不匹配 #.,然后匹配 #

然后重复该部分,然后重复点,然后重复该部分直到字符串结尾:

^[^#.]*#[^.#]+\.[^.#]*$

Regex demo

说明

  • ^ 字符串开头
  • [^#.]*# 匹配 0+ 次不是 #. 然后匹配 #
  • [^.#]+\. 匹配 1+ 次不是 .# 然后匹配一个点
  • [^.#]* 匹配 0+ 次不是 .#
  • $ 字符串结束

let pattern = /^[^#.]*#[^.#]+\.[^.#]*$/;
[
  "abc#.123",
  "abc#12.3",
  "abc#abcd.23",
  "a#123.12",
  "a#12123124.12",
  "abcd#1231.09",
  "1.23#12312.01",
  "123#122.01#12"
].forEach(s => console.log(s + ": " + pattern.test(s)))

您可以使用此正则表达式确保字符串中的第一个 # 后跟一个点 .,其中 #. 之间的间隔为一个或多个字符,

^[^#]*#[^.]+\.

解释:

  • ^ - 字符串开始
  • [^#]* - # 以外的零个或多个字符,如果您希望点也不出现在 # 之前,则可以将其更改为 [^#.]*
  • # - 匹配第一个 # 字符
  • [^.]+ - 匹配除点
  • 以外的一个或多个字符
  • \. - 匹配文字点

Regex Demo

JS代码演示,

const arr = ['abc#.123','abc#12.3','abc#abcd.23','a#123.12','a#..dd']

arr.forEach(s => console.log(s + " --> " + /^[^#]*#[^.]+\./.test(s)))