0

I'm extracting a string of numbers The numbers are either 7 digits or they are 9 digits. Exactly 7, or exactly 9. If it's 8 or its 10 I don't want it to extract anything. I've tried looking on here and none of the expressions are working for me. I've tried the following.

/[0-9]{7}|[0-9]{9}/ 

-- This gives me the first 7 digits only. If it is 8 digits or 9 digits I only get the first 7.

/[0-9]{7}([0-9]{2})?/ 

-- Will give me 7 digits. If it is 8 digits it gives me the first 7. If it is 9 digits it gives me 9. I need only 7, or only 9.

/^(\d{7}|\d{9})$/  

-- Doesn't work at all unless I remove the carrot and the $, and then it works just like the first expression example.

I don't understand why | as an "or" isn't working.

I know \d is the modern regex shorthand, but the application cannot compile that way. I get an error saying "Don't escape other characters than of "[].\ (){}?+*<>|^"." .

  • This will match 7 or 9 digits `^\d{7}(?:\d{2})?$` – The fourth bird Sep 15 '21 at 17:47
  • I get the following result. Can't compile Regular Expression: Can't parse cardinality at this position. Got stuck with: "?:[0-9]{2}" Again, I have to change "\d" to old school "[0-9]" as it thinks I'm trying to escape characters. – John Parham Sep 15 '21 at 17:52
  • /[^\d][0-9]{7}[^\d]|[^\d][0-9]{9}[^\d]/ – jdweng Sep 15 '21 at 17:53
  • So close. This works for 9 digits, but doesn't give me a value if the string is 7 digits. This will also give me the first 9 digits if the string is more than 9 digits. – John Parham Sep 15 '21 at 17:55
  • Use numeric boundaries, `(?<!\d)\d{7}(?:\d{2})?(?!\d)` – Wiktor Stribiżew Sep 15 '21 at 18:11
  • Can't compile Regular Expression: Can't parse cardinality at this position. Got stuck with: "?<!\d" – John Parham Sep 15 '21 at 18:14
  • This Almost works. /[0-9]{7}([0-9]{2})?/ If the test is 7 digits I get 7. If the test is 9 digits I get 9. BUT if the test is 8 digits I get the first 7. Is there a way to make it not extract if it is 8 digits? – John Parham Sep 15 '21 at 18:20

0 Answers0