Search code examples
javascriptregexregex-negationregex-lookaroundsregex-greedy

RegEx for checking character X places after another character


I have done a very basic step which checks for the presence of one special character. The next step needs some advice as I want to be able to search for another special character starting from 1 places after finding #.

var reg = /#/;
alert(reg.test(string))

For example:

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 .

So that gap between # and . should always be 1 or more characters with # always coming first.


Solution

  • You could assert the start of the string ^, match not a # or . using a negated character class [^#.], then match #.

    Then repeat that part but then for the dot and then repeat that part until the end of the string:

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

    Regex demo

    Explanation

    • ^ Start of string
    • [^#.]*# Match 0+ times not # or . then match #
    • [^.#]+\. Match 1+ times not . or # then match a dot
    • [^.#]* Match 0+ times not . or #
    • $ End of string

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