Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

regex - JavaScript regular expression (Page range validation)

Yesterday I've got a task to implement a validation on the field where user can enter the range of pages that he wants to download.

After reading some tutorials, I've created such pattern which in my opinion should work, but it doesn't :(

Can you give me a hint where is the mistake, or how it should be done in the better way.

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

P.S. You can test it here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_regexp_test

More examples:

  • 1 match
  • 1-2 match
  • -2 not match
  • 1, 2-3, 4, 5-7 match
  • 1 2, 3 not match
  • 1-2-2 not match

etc... like in MS Office or Adobe PDF Reader

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to escape the backslashes in the string, or JavaScript will strip them out or interpret them as escape sequences:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...