How to write proper regex finding my pattern

Viewed 57

I want to find links with text in big string. I'm looking for such pattern: [text](url), for example

[Check it on stackoverflow](https://stackoverflow.com/)

I have regex which finding mostly good results but there is problem when this pattern is enclosed in brackets like

This is our forum ([Check it on stackoverflow](https://stackoverflow.com/) maybe you can help)

Regex: /\[(.*)\](\(.*.*?\))/

I do need to put sentence between .* like .*stackoverflow.*.

Is there possibility to stop regex after first )?

2 Answers

as comments previously have mentioned .*.*? doesn't make sense and you could use a negaged character class [^()]* instead.

/\[(.*)\](\([^()]*\))/

check this online example with your test data https://rubular.com/r/lte0WSKCByNXOf

You can use a negated character class for both the square brackets and the parenthesis. In that case there are no non greedy quantifiers required.

If you want to put in a word to match between the square brackets:

\[([^][]*\bstackoverflow\b[^][]*)]\(([^()]*)\)

As you tagged php, see a regex demo with pcre selected.

Without the word:

\[([^][]*)]\(([^()]*)\)

Regex demo

Related