Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: 5 digits in increasing order

Tags:

regex

I need a regex for 5 digits in increasing order, like 12345, 24579, 34680, and so on.

0 comes after 9.

like image 838
DEACTIVATIONPRESCRIPTION.NET Avatar asked Jul 03 '10 13:07

DEACTIVATIONPRESCRIPTION.NET


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.

What does D+ mean in regex?

\d is a digit (a character in the range [0-9] ), and + means one or more times. Thus, \d+ means match one or more digits. For example, the string "42" is matched by the pattern \d+ .

How do you find digits in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).


1 Answers

You can try (as seen on rubular.com)

^(?=\d{5}$)1?2?3?4?5?6?7?8?9?0?$

Explanation

  • ^ and $ are the beginning and end of string anchors respectively
  • \d{5} is the digit character class \d repeated exactly {5} times
  • (?=...) is a positive lookahead
  • ? on each digit makes each optional

How it works

  • First we use lookahead to assert that anchored at the beginning of the string, we can see \d{5} till the end of the string
  • Now that we know that we have 5 digits, we simply match the digits in the order we want, but making each digit optional
    • The assertion ensures that we have the correct number of digits

regular-expressions.info

  • Anchors, Character Classes, Finite Repetition, Lookarounds, and Optional

Generalizing the technique

Let's say that we need to match strings that consists of:

  • between 1-3 vowels [aeiou]
  • and the vowels must appear in order

Then the pattern is (as seen on rubular.com):

^(?=[aeiou]{1,3}$)a?e?i?o?u?$

Again, the way it works is that:

  • Anchored at the beginning of the string, we first assert (?=[aeiou]{1,3}$)
    • So correct alphabet in the string, and correct length
  • Then we test for each letter, in order, making each optional, until the end of the string

Allowing repetition

If each digit can repeat, e.g. 11223 is a match, then:

  • instead of ? (zero-or-one) on each digit,
  • we use * (zero-or-more repetition)

That is, the pattern is (as seen on rubular.com):

^(?=\d{5}$)1*2*3*4*5*6*7*8*9*0*$
like image 162
polygenelubricants Avatar answered Oct 11 '22 19:10

polygenelubricants