regex allows one character (it should not) why?

前端 未结 2 708
春和景丽
春和景丽 2021-01-28 22:33

Hello I am trying to create a regex that recognizes money and numbers being inputted. I have to allow numbers because I am expecting non-formatted numbers to be inputted program

2条回答
  •  生来不讨喜
    2021-01-28 23:03

    The "regular expression" you're using in your example script isn't a RegExp:

    $(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" });
    

    Rather, it's a String which contains a pattern which at some point is being converted into a true RegExp by your library using something along the lines of

    var RE=!(value instanceof RegExp) ? new RegExp(value) : value;
    

    Within Strings a backslash \ is used to represent special characters, like \n to represent a new-line. Adding a backslash to the beginning of a period, i.e. \., does nothing as there is no need to "escape" the period.

    Thus, the RegExp being created from your String isn't seeing the backslash at all.

    Instead of providing a String as your regular expression, use JavaScript's literal regular expression delimiters.

    So rather than:

    $(this).inputmask('Regex', { regex: "[\$]?([0-9,])*[\.][0-9]{2}" });
    

    use

    $(this).inputmask('Regex', { regex: /[\$]?([0-9,])*[\.][0-9]{2}/ });
    

    And I believe your "regular expression" will perform as you expect.

    (Note the use of forward slashes / to delimit your pattern, which JavaScript will use to provide a true RegExp.)

提交回复
热议问题