What I'm trying to do is get the text and url out of a string like this:
This is a title [http://awebsite.com/a/download.zip]
This is the regex I am using:
/(.*?)[(.*?)]/
I know what the problem is... the first (.*?)
is matching the whole string! But I'm not sure how to only get it to match upto the first [
occurance.
An explanation of what I'm doing wrong and how to fix would be good thank you. I WILL eventually learn regex!
Thanks guys
PS: using php and the preg_match
function.
[(.*?)]
is a character class and matches one of: '('
, '.'
, '*'
, '?'
or ')'
.
You need to escape the [
causing it to match a literal '['
(and the ]
is not special, so it doesn't need escaping).
/(.*?)\[(.*?)]/
You've almost got it, but try escaping the grouping characters [ and ], so you'll get:
/(.*?)\[(.*?)\]/
Your problem is not the first part rather the second part.
You have to escape the [ like this :
/(.*?)\[(.*?)]/
Explanation :
"
( # Match the regular expression below and capture its match into backreference number 1
. # Match any single character
*? # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
\[ # Match the character “[” literally
( # Match the regular expression below and capture its match into backreference number 2
. # Match any single character
*? # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
] # Match the character “]” literally
"
You need to escape to []
characters:
/(.*?)\[(.*?)\]/