72

Is there a better way to represent a fix amount of repeats in a regular expression?

For example, if I just want to match exactly 14 letters/digits, I am using ^\w\w\w\w\w\w\w\w\w\w\w\w\w\w$ which will match a word like UNL075BE499135 and not match UNL075BE499135AAA is there a handy way to do it? I am currently doing it in Java, but I guess this may apply to other language as well.

starball
  • 20,030
  • 7
  • 43
  • 238
Ken
  • 3,922
  • 9
  • 39
  • 40

4 Answers4

105

For Java:

Quantifiers documentation

X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}

kajacx
  • 12,361
  • 5
  • 43
  • 70
shookster
  • 1,671
  • 1
  • 12
  • 10
36

The finite repetition syntax uses {m,n} in place of star/plus/question mark.

From java.util.regex.Pattern:

X{n}      X, exactly n times
X{n,}     X, at least n times
X{n,m}    X, at least n but not more than m times

All repetition metacharacter have the same precedence, so just like you may need grouping for *, +, and ?, you may also for {n,m}.

  • ha* matches e.g. "haaaaaaaa"
  • ha{3} matches only "haaa"
  • (ha)* matches e.g. "hahahahaha"
  • (ha){3} matches only "hahaha"

Also, just like *, +, and ?, you can add the ? and + reluctant and possessive repetition modifiers respectively.

    System.out.println(
        "xxxxx".replaceAll("x{2,3}", "[x]")
    ); "[x][x]"

    System.out.println(
        "xxxxx".replaceAll("x{2,3}?", "[x]")
    ); "[x][x]x"

Essentially anywhere a * is a repetition metacharacter for "zero-or-more", you can use {...} repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use * because Java doesn't officially support infinite-length lookbehind.

References

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
21

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

eldarerathis
  • 35,455
  • 10
  • 90
  • 93
1

In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$"); for further information see the javadoc

Jano González
  • 14,536
  • 1
  • 16
  • 9