我在想如何將這個確切的php正則表達式功能改成javascript?將此正則表達式轉換爲javascript
$ismatch= preg_match('|She is a <span><b>(.*)</b></span>|si', $sentence, $matchresult);
if($ismatch)
{
$gender= $matchresult[1];
}
else{ //do other thing }
我在想如何將這個確切的php正則表達式功能改成javascript?將此正則表達式轉換爲javascript
$ismatch= preg_match('|She is a <span><b>(.*)</b></span>|si', $sentence, $matchresult);
if($ismatch)
{
$gender= $matchresult[1];
}
else{ //do other thing }
由於JavaScript不支持s
修飾符,因此這並不是微不足道的。
等效regex對象將是
/She is a <span><b>([\s\S]*)<\/b><\/span>/i
代碼(來自如果存在匹配的匹配提取第1組)的功能將在JavaScript來完成這樣的:
var myregexp = /She is a <span><b>([\s\S]*)<\/b><\/span>/i;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1];
} else {
// do other thing
}
關於'[\ s \ S]'方法的信息可以在[MDN]找到(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp):*(小數點)匹配任何除換行符外的單個字符:'\ n''\ r''\ u2028'或'\ u2029'。 ('[\ s \ S]'可以用來匹配任何字符,包括換行符。)* – 2012-03-04 11:34:50
或者使用特殊的JS特性'[^]',它匹配任何字符。 – Qtax 2012-03-04 11:50:04
@Qtax:哇,我以前從未見過這個。有沒有關於這方面的文件? – 2012-03-04 12:15:31
爲新聞,JS不支持dotall開關http://stackoverflow.com/questions/1068280/javascript-regex-multiline-flag-doesnt-work – Petah 2012-03-04 11:33:12
這可能是一個很好的問題,如果措詞得當,重點是在dotall修飾符......在其當前狀態下,它聽起來像是「爲我工作」問題ñ。 – 2012-03-04 11:36:33