Faizan Anwer Ali
Faizan Anwer Ali

Reputation: 671

Regex get all before first occurrence of character

I know it's been asked many many times. I tried my best but the result wasn't perfect.

Regex

/(\(\s*["[^']*]*)(.*\/logo\.png.*?)(["[^']*]*\s*\))/gmi

Regex101 Link: https://regex101.com/r/0f8Q08/1

It should capture all separately.

(../asdasd/dasdas/logo.png) 
(../asdasd/dasdas/logo.png) 
( '../logo.png' ) 

Right now it's capturing as a whole.

(../asdasd/dasdas/logo.png) (../asdasd/dasdas/logo.png) ( '../logo.png' ) 

What I need is, the regex to stop after the first closing bracket ) match.

wrong text capture

Upvotes: 1

Views: 386

Answers (3)

The fourth bird
The fourth bird

Reputation: 163577

The issue in your pattern is that the .* matches too much. After the opening parenthesis, you should exclude matching the ( and ) to overmatch the separate parts.

You don't need all those capture groups if you want to match the parts with parenthesis as a whole.

You can use 1 capture group, where the group would be a backreference matching the same optional closing quote.

\(\s*(["']?)[^()'"]*\/logo\.png[^()'"]*\1\s*\)

Regex demo

If you also want the matches without the matching quotes:

\(\s*["']?[^()'"]*\/logo\.png[^()'"]*["']?\s*\)

Regex demo

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You can use

(\(\s*(["']?))([^"')]*\/logo\.png[^"')]*)(\2\s*\))

See the regex demo.

Details

  • (\(\s*(["']?)) - Group 1: (, any zero or more whitespaces, and then Group 2 capturing either a ' or a " optionally
  • ([^"')]*\/logo\.png[^"')]*) - Group 3: any zero or more chars other than ", ' and ), then a /logo.png string, and then again any zero or more chars other than ", ' and )
  • (\2\s*\)) - Group 4: the same value as in Group 2, zero or more whitespaces, and a ) char.

Upvotes: 1

depperm
depperm

Reputation: 10756

If you want to use regex you can make the change from .* to [^)] so you stay between parenthesis

(\(\s*["[^']*]*)([^)]*\/logo\.png.*?)(["[^']*]*\s*\))

regex101

Upvotes: 0

Related Questions