Kudlas
Kudlas

Reputation: 659

Parse url with regexp, pattern doesnt match optional string

I've got these strings I want to parse:

?forum=Jiné akce a jiné#comments
?trening=140#$|Pralinka
?novinka=87#comments
?forum=Mimo mísu#comments
?forum=Členské forum#comments
?trening=139#comments

and I want to output array like

 1. forum 
 2. Jiné akce a jiné
 3. comments

or

 1. trening
 2. 140
 3. Pralinka

So I wrote following regexp:

\?([a-z]{4,})\=(.+)\#(\$\|)?([a-z]+)

Regex101

But It's not working in second case (optional string part).

Upvotes: 1

Views: 67

Answers (3)

Robin
Robin

Reputation: 9644

Remember that by default, regex are case sensitive... So [a-z] can't match Pralinka. You can fix that by using the i (case insensitive) flag, or with:

\?([a-z]{4,})=(.+)#(?:\$\|)?([A-Za-z]+)

Notice that there is no need to escape the = or the # (we're not in free spacing mode), and I added a non capturing group (?:...) so that Pralinka will be in the same capturing group as comment.

The demo is here

Upvotes: 3

medokin
medokin

Reputation: 620

You need to add a global flag: /g.

http://regex101.com/r/vR0oM4

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

[a-z]+ does not match Pralinka because P is an uppercase letter.

Fixed regex

Upvotes: 2

Related Questions