簡體   English   中英

逆向工程正則表達式模式以查找令牌數量和預期匹配項的長度

[英]Reverse-engineer regex pattern to find number of tokens and length of expected matches

為了驗證表單中的某些字段,我需要找到特定正則表達式指定的令牌數量,以及該正則表達式指定的匹配長度。 例如,

  1. 使用模式[0-9]{3},[0-9]{2} ,我需要找到5個長度和2個令牌。
  2. 使用模式[0-9]{2}/[0-9]{2}/[0-9]{4} ,我需要找到8的長度和3的令牌數。

誰能指出這樣做的方向?

盡管您沒有要求使用正則表達式解決此問題,但我們會的。 在正則表達式上運行的正則表達式! 那是正則表達式嗎?

乍一看,任務聽起來很復雜。 我們需要編寫一個正則表達式引擎來解析您的表達式嗎?

幸運的是,如果您的所有量詞都在{curlies}內部,那么有一個簡單的解決方案。 如果我們匹配curl之間的所有數字,則匹配數將為令牌數,而長度將為匹配之和。

我們簡單的正則表達式

{(\d+)}

好的,但是我們如何在代碼中實現呢?

這是一個完整的腳本,可以輸出令牌的數量和長度。 請參閱在線演示的結果。

<script>
var subject = '[0-9]{2}/[0-9]{2}/[0-9]{4}';
var regex = /{(\d+)}/g;
var group1Caps = [];
var match = regex.exec(subject);

// Place Group 1 captures in an array
while (match != null) {
    if( match[1] != null ) group1Caps.push(match[1]);
    match = regex.exec(subject);
}

// How many tokens are there?
document.write("*** Number of Tokens ***<br>");
document.write(group1Caps.length);

// What length are the expected matches?
var counter = 0;
document.write("<br>*** Length of Expected Matches ***<br>");
if (group1Caps.length > 0) {
   for (key in group1Caps) counter += parseInt(group1Caps[key]);
   }
document.write(counter,"<br>")   
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM