简体   繁体   中英

How does this regex pattern work

I am learning regex and I am currently looking at this page http://regexone.com/example/0 I am following everything ok so far but I dont understand how this one works

^-?\d+(,\d+)*(\.\d+(e\d+)?)?$

It matches the following text:

  • 3.14529
  • -255.34
  • 128
  • 1.9e10
  • 123,34.00

And skips this one:

  • 720p

The solution explains it like this

For the above example, the expression '^-?\\d+(,\\d+)*(.\\d+(e\\d+)?)?$' will match a string that starts with an optional negative sign, one or more digits, optionally followed by a comma and more digits, followed by an optional fractional component which consists of a period, one or more digits, and another optional component, the exponent followed by more digits.

The * is where I get confused. I read it like this:

^                 Start
-?                Optional Negative
\d+               One or more digits
(,\d+)*           Group-comma and one or more digits - the * confuses me here
(\.\d+(e\d+)?)?   Optional group of full stop, one or more digits, another optional group of e and 1 or more digits

As I said the * confuses me. I think it is something to do with Variable content but I dont understand how it works.

The * is simply a quantifier that states: 'match 0 or more of the previous match', in this case (,\\d+) .

In this case, it would match something like:

,123,123,123,63,345,345,346,3245235,234  (of any length but similar pattern)

正则表达式可视化

Debuggex Demo

that means that zero or more times a group like this ,34 is allowed.

group like ,34 or ,666 is represented as (,\\d+)*

so that it allows text 122,222,12 or 323,212,22

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