我有一个看起来像这样的字符串:
var complicatedString = "<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/32.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Sunny\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Fri - Sunny. High: 23Low: 13\n<BR /> Sat - Thunderstorms. High: 25Low: 15\n<BR /> Sun - Thunderstorms. High: 28Low: 21\n<BR /> Mon - Partly Cloudy. High: 24Low: 17\n<BR /> Tue - Partly Cloudy. High: 26Low: 18\n<BR />\n<BR />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-23511893/\">Full Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)\n<BR />\n]]>"
我需要提取 http://l.yimg.com/a/i/us/we/52/32.gif 强>。我想出的正则表达式是:
var re = /(alt|title|src)=(\\"[^"]*\")/i;
参见 fiddle :https://jsfiddle.net/47rveu62/2/
我不确定为什么,但这行不通。
var re = /(alt|title|src)=(\\"[^"]*\")/i;
var m;
do {
m = re.exec(complicatedString);
} while(m !== null);
更新:Regex 101 声称它有效 https://regex101.com/r/oV2hO2/1
最佳答案
问题出在正则表达式上。
字符串中的反斜杠用于转义双引号字符串中的双引号。 反斜杠是转义字符而不是字符串的一部分。因此,在正则表达式中不需要这些字符。
var re = /(alt|title|src)=(\\"[^"]*\")/i;
^^ ^ // Remove those
使用
/(alt|title|src)=("[^"]*")/gi;
此处的g
标志是必需的,因为正则表达式的lastIndex
属性未被RegExp#exec
更新。下一次迭代,正则表达式将从相同的索引开始搜索,从而进入无限循环。
MDN
var complicatedString = "<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/32.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Sunny\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Fri - Sunny. High: 23Low: 13\n<BR /> Sat - Thunderstorms. High: 25Low: 15\n<BR /> Sun - Thunderstorms. High: 28Low: 21\n<BR /> Mon - Partly Cloudy. High: 24Low: 17\n<BR /> Tue - Partly Cloudy. High: 26Low: 18\n<BR />\n<BR />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-23511893/\">Full Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)\n<BR />\n]]>";
var re = /(alt|title|src)=("[^"]*")/gi;
var m;
while(m = re.exec(complicatedString)) {
console.log(m[2]);
}
我建议您使用以下正则表达式
/img.*?src=("|')(.*?)\1/i;
var complicatedString = "<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/32.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Sunny\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Fri - Sunny. High: 23Low: 13\n<BR /> Sat - Thunderstorms. High: 25Low: 15\n<BR /> Sun - Thunderstorms. High: 28Low: 21\n<BR /> Mon - Partly Cloudy. High: 24Low: 17\n<BR /> Tue - Partly Cloudy. High: 26Low: 18\n<BR />\n<BR />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-23511893/\">Full Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)\n<BR />\n]]>";
var regex = /img.*?src=("|')(.*?)\1/i;
var match = complicatedString.match(regex)[2];
console.log(match);
关于javascript - 使用正则表达式从字符串中提取图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751281/