[英]PHP regular expressions to Javascript within if statements
我了解如何在JS和PHP中使用正則表達式。 我正在嘗試將我的一些PHP代碼切換為JS,並且我有一個函數,該函數通過不同的正則表達式來查看它是否可以找到匹配項。
示例PHP:
if(preg_match('/regex1/', $string, $matches)) {
$output = $matches[1];
} else if(preg_match('/regex2/', $string, $matches)) {
$output = $matches[1];
} else etc....
有沒有辦法在JS中做類似的事情?
我能想到的唯一方法是:
if(string.match(/regex/)) {
var res = string.match(/regex/);
output = res[1];
} else if ..... and so on
我寧願不要讓它參加兩次比賽……還有另一種方法嗎?
謝謝你的幫助。
您可以這樣做:
var res;
if(res = string.match(/regex/)) {
output = res[0];
} else if ..... and so on
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
您可以構建如下的正則表達式數組:
var array = ["/regex1/", "/regex2/", "/regex3/", "/regex4/"];
var x;
for (index = 0; index < array.length; ++index) {
if(string.match(array[index]))){
x++;
output = matches[x];
}
}
看一下MDN關於正則表達式的文檔,特別是可用的方法 。 我認為您想要的是exec
方法而不是match,因為它將返回匹配結果的數組,就像PHP中的preg_match
一樣。 您可能首先需要存儲exec
調用的結果,然后在您的條件下應檢查結果的長度。
var matches = mystring.exec(/regex1/);
var output;
if (matches.length) {
output = matches[0];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.