“Simple"regex不像我想要的那样工作


"Simple" regex doesn't work how I want it to?

我要做的就是从字符串中获取文本和url,就像这样:

这是个标题[http://awebsite.com/a/download.zip]

这是我使用的正则表达式:

/(.*?)[(.*?)]/

我知道问题是什么…第一个(.*?)匹配整个字符串!但是我不确定如何只让它匹配到第一个[出现。

解释一下我做错了什么以及如何修复会很好,谢谢。我最终学会正则表达式!

谢谢大家

PS:使用php和preg_match函数

你的问题不是第一部分,而是第二部分。

你必须像这样转义[:

/(.*?)'[(.*?)]/

说明:

    "
(       # 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
"

[(.*?)]是一个字符类,匹配'(''.''*''?'')'中的一个。

您需要转义[,使其与文字'['匹配(并且]不是特殊的,因此不需要转义)。

/(.*?)'[(.*?)]/

见:http://www.regular-expressions.info/charclass.html

您几乎已经得到了它,但是尝试转义分组字符[和],因此您将得到:

/(.*?)'[(.*?)']/

需要转义为[]字符:

/(.*?)'[(.*?)']/