Jeff
Jeff

Reputation: 2423

How to use regex to capture groups

I have a string:

tel:+13172221234;foo=1234;bar=000-000-000;wombat=mydomain.com

Note that the string always begins with tel:+{{some-number}}. I want to capture so that I have the following:

+13172221234
foo
1234
bar
000-000-000
wombat
mydomain.com

What I have is this: ([^?=&;]+)=([^;]*) which returns three matches, each with a variable and a value (i.e., foo/1234). However I cannot seem to capture the number in front. I would think that simply putting a tel:(\w+) in front would do it but it doesn't work.

https://regex101.com/r/cM2pQ5/2

Anyone able to help? Maybe I should just do two separate regexes?

Upvotes: 1

Views: 88

Answers (4)

anubhava
anubhava

Reputation: 785856

You can use this lookahead based regex:

([^:?=&;]+)(?=[=;])(?:=([^;]*))?

RegEx Breakup:

(             # Start of capture group #1
   [^:?=&;]+  # Match 1 or more char of anything but ? or = or & or ;
)             # End of capture group #1
(?=           # Start of positive lookahead
   [=;]       # to assert next position is either = or ;
)             # End of positive lookahead
(?:           # Start of "optional" non-capturing group
   =          # match literal =
   (          # Start of capture group #2
      [^;]*   # match 0 or more of any char that is not a ;
   )          # End of capture group #2
)?            # Start of non-capturing group. ? in the end makes it optional

RegEx Demo

Upvotes: 4

svsd
svsd

Reputation: 1869

Here's one more way: (regex101)

^tel:([^;]+)|;([^=]+)=([^;]+)

This has two parts - the first part only matches the start of the string and the second part matches the rest of the key value pairs. I'm assuming that your string starts with tel:

Upvotes: 1

Bohemian
Bohemian

Reputation: 425278

I would simply match this:

[^;=]+

Upvotes: 1

Thomas Ayoub
Thomas Ayoub

Reputation: 29451

As you can face or = or : as a Key/Value separator I suggest this:

([^?=&;]+)(=|:)([^;]*)

Upvotes: 2

Related Questions