0

I need to create a regular expression that matches a process number that has the following pattern #######-##.####.7.09.0009 where # means numbers from 0 to 9. Here is what I came up with after some research:

var regex = new RegExp("^[0-9]{7}[\-][0-9]{2}[\.][0-9]{4}[\.7\.09\.0009]$");

I also tried:

  • /^[0-9]{7}\-[0-9]{2}\.[0-9]{4}\.7\.09\.0009$/
  • /^[0-9]{7}\\-[0-9]{2}\\.[0-9]{4}\\.7\\.09\\.0009$/
5
  • 2
    You don't have to put [\.7\.09\.0009] in square brackets or else it would mean a character class. Commented Sep 27, 2018 at 18:21
  • So what is the issue? Commented Sep 27, 2018 at 18:21
  • You have to double-escape backslashes when using new RegExp(String) Commented Sep 27, 2018 at 18:22
  • 1
    visualize it and you will see what it actually is doing Commented Sep 27, 2018 at 18:22
  • 1
    Your second pattern works using anchors to assert the start and the end of the line. Commented Sep 27, 2018 at 18:39

1 Answer 1

4

Try this:

const pattern = /\d{7}\-\d{2}\.\d{4}\.7\.09\.0009/

Regexper is a great tool that I use whenever I'm writing a regular expression, I find it really helps to visualize what the expression is actually doing. Check it out.

For reference, here is the original pattern that you posted -- it looks like the main problem is that you are defining character classes in several places using [ and ] where you really don't need them at all.

Sign up to request clarification or add additional context in comments.

2 Comments

So I should do const pattern = /\d{7}\-\d{2}\.\d{4}\.7\.09\.0009/ and then regex = new RegExp(pattern) ? Maybe the problem lies somewhere else then because alert(/\d{7}\-\d{2}\.\d{4}\.7\.09\.0009/.test($('#numero-processo').val())); returns false. Here is what alert($('#numero-processo').val()); returns 1111111-11.1111.7.09.009 Shouldn't it be working?
Nah, pattern is a regex literal (developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…) so you don't need new RegExp(pattern), you can just do pattern.test. What you posted is expected behavior though - "1111111-11.1111.7.09.009" does not match the regex (it should end with "0009", like this: "1111111-11.1111.7.09.0009")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.