JavaScript regular expression (page range checking)

Yesterday I had a task to perform a check in a field where the user can enter the range of pages that he wants to load.

After reading some lessons, I created a template that, in my opinion, should work, but it’s not: (

Can you give me a clue where the error is, or how it should be done better.

<script type="text/javascript">
var patt1=new RegExp("^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$");
document.write(patt1.test("1, 2, 3-5, 6, 8, 10-12"));
</script>

PS You can check it here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_regexp_test

Other examples:

  • 1 corresponds
  • 1-2 compliance
  • -2 does not match
  • 1, 2-3, 4, 5-7 correspond
  • 1 2, 3 do not match
  • 1-2-2 do not match

etc., for example, in MS Office or Adobe PDF Reader

+3
4

, JavaScript escape-:

var patt1 = new RegExp("^(\\s*\\d+\\s*\\-\\s*\\d+\\s*,?|\\s*\\d+\\s*,?)+$");
+7

:

^(\d+(-\d+)?)(,\d+(-\d+)?)*$

:

^(\s*\d+\s*(-\s*\d+\s*)?)(,\s*\d+\s*(-\s*\d+\s*)?)*$

+4

patt1 new RegExp, literal. "\" ( "\\" ).

var patt1 = /^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$/g;

patt1.test("1, 2, 3-5, 6, 8, 10-12") true, patt1.test("1, 2, 3-5, 6, 8, 10-12,nocando") false

+1

^((\\d+(\\-\\d+)?, ?)*(\\d+(\\-\\d+)?))+$

0

Source: https://habr.com/ru/post/1780821/


All Articles