Match all repeating occurrences regex

70 views Asked by At

I need to match following string separated by whitespaces starting with "Token" .
Example string

Token token=12eqddsfasdsa [email protected] app_id=2312edsdas

I have tried several expressions.

^Token (\w*=[^-\s]+)

Captures only one first match.

^Token(\s\w*=[^-\s]+)+

This expression captures only last.

I need to capture

match[0] = token=12eqddsfasdsa
match[1] = [email protected]
match[2] = app_id=2312edsdas

I know there is easy way to achieve this result, but I am not experienced enough to get it.
Please help with this.

2

There are 2 answers

1
Federico Piazza On BEST ANSWER

You are facing the common problem of capturing content for repeated groups, so I would use two regexes for this:

1- First to detect the line starting with Token pattern using this regex:

^Token

2- To extract the matches you are interesting in using another regex (like yours):

(\w*=[^-\s]+)

You can use a code like this

$str = <your string>
if (preg_match("/^Token/", $str)) {
    preg_match_all('/(\w*=[^-\s]+)/', $str, $matches);
}

Match information

MATCH 1
1.  [6-25]  `token=12eqddsfasdsa`
MATCH 2
1.  [26-50] `[email protected]`
MATCH 3
1.  [51-68] `app_id=2312edsdas`
0
Atang Sutisna On

I think the simple way is using explode function.

$str = "Token token=12eqddsfasdsa [email protected] app_id=2312edsdas";
$result = explode(" ", $str);

The result will be like this:

Array ( [0] => "Token" [1] => "token=12eqddsfasdsa". [2] => "[email protected]"  [3] => "app_id=2312edsdas")