简体   繁体   中英

How to set repeat regular expression?

I have regular expression ^\\d{5}$|^\\d{5}-\\d{4}*$" it checked US zip. But I need check " zip, zip, zip " how to do this?

I tried this ^(\\d{5}$|^\\d{5}-\\d{4},)*$ but it not work

Try

((^|, )(\d{5}|\d{5}-\d{4}))*$

Tester: http://regexr.com?36297

Each match must be preceded by (^|, ) , so by the beginning of the string or a , (comma space)

Note that you shouldn't use the \\d in .NET, because ٠١٢٣٤ are \\d ! (in .NET \\d includes non-ASCII Unicode digits). [0-9] is normally better.

The expression you appear to need is:

    ^\d{5}(|-\d{4})(,\d{5}(|-\d{4}))*$

The one you were attempting to write was:

    ^(\d{5}|\d{5}-\d{4},)*$

but that would require every ZIP to have a trailing comma, which the very last one would not have had.

Breaking down the answer given,

  • \\d{5}(|-\\d{4}) is a variant of your original, but simply making the -1234 optional.
  • (,\\d{5}(|-\\d{4}))* is the first regular expression preceded by a comma, and allowed zero or more times.

I would use this for speed:

 ^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$

expanded

 ^ 
 \d{5} 
 (?: - \d{4} )?
 (?:
      , \s* \d{5} 
      (?: - \d{4} )?
 )*
 $

and this for speed/flexibility:

 ^\s*\d{5}(?:\s*-\s*\d{4})?(?:\s*,\s*\d{5}(?:\s*-\s*\d{4})?)*\s*$

expanded

 ^ 
 \s* 
 \d{5} 
 (?: \s* - \s* \d{4} )?
 (?:
      \s* , \s* \d{5} 
      (?: \s* - \s* \d{4} )?
 )*
 \s* 
 $

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM