Pierce McGeough
Pierce McGeough

Reputation: 3086

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:

And skips this one:

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.

Upvotes: 1

Views: 113

Answers (2)

aelor
aelor

Reputation: 11116

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

Upvotes: 0

sshashank124
sshashank124

Reputation: 32189

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)

Regular expression visualization

Debuggex Demo

Upvotes: 2

Related Questions