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

时间:2019-05-18 15:27:44

标签: javascript regex regex-negation regex-lookarounds regex-greedy

我做了一个非常基本的步骤,检查一个特殊字符的存在。下一步需要一些建议,因为我希望能够在找到#后从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个或多个字符,而#始终在前。

3 个答案:

答案 0 :(得分:2)

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

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

#

Regex demo

说明

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

$

答案 1 :(得分: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)));

答案 2 :(得分:1)

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

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

说明:

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

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)))