簡體   English   中英

為兩個字符定義一個正則表達式,然后是兩個數字

[英]Defining a regex for two characters then two numbers

我在我的 React 應用程序中使用正則表達式來驗證表單條目的輸入。 輸入使用 onChange 偵聽器調用 function 設置 state 字符更改。

有效輸入是兩個字符后跟兩個數字。 即RD01或EX12

我已經通過重新工作對其進行了調查。 它匹配正確的大小寫,盡管它也僅適用於兩位數。 即 01 或 12

    const onAssetChange = (e) => {
        const input = e.target.value.toUpperCase()
        const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
        if (!input || input.match(re)) {
            setAssetID(input)
        }
    }

正則表達式需要能夠更新每個按鍵,因為它會在每個更改事件上更新 state。

嘗試使用[AZ]{2}[0-9]{2}正則表達式。

您的正則表達式中的錯誤是{0,2}量詞匹配提供的字符集中的 0 到 2 個元素。 請改用{2} 這將斷言檢查 2 個字符集計數。

我的建議是使用 mockFunction 將您的輸入更新為 tme 所需的標准,例如將HI as HI00AA as AA00Aa as Aa00等,並測試這個模擬字符串。 這是相同的示例。

 console.log('R -- ', mockInput('R')); console.log('RD --', mockInput('RD')); console.log('RD0 -- ', mockInput('RD0')); console.log('RD01 -- ', mockInput('RD01')); console.log('01 -- ', mockInput('01')); console.log('R01 -- ', mockInput('R01')); console.log('RD011 -- ', mockInput('RD011')); function mockInput(input) { const returnStr = "AA00"; const fakeInput = input.length >= 4? input: input + returnStr.substring(input.length, 4); const re = RegExp(/[AZ]{2}[0-9]{2}/); let status = false; if (re.test(fakeInput)) { status = true; } return status; };

RegExp('^[AZ]{0,2}[0-9]{0,2}$')將檢查012字符。 數字也是如此,因此即使A1也是有效的。 嘗試以下操作:

const re = new RegExp('^[A-Z]{2}[0-9]{2}$')

您可以使用'^[AZ][AZ][0-9][0-9]$'

這應該工作...

const onAssetChange = (e) => {
    const input = e.target.value.toUpperCase()
    const re = new RegExp('^\w{2}\d{2}$')
    if (!input || input.match(re)) {
        setAssetID(input)
    }
}

好吧,不好看……

    const onAssetChange = (e) => {
        const input = e.target.value.toUpperCase()
        const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
        if (!input || input.match(re) && (input.length < 2 ? input[0].match(/[A-Z]/) : input.slice(0,2).match(/[A-Z][A-Z]/)) ) {
            setAssetID(input)
        }
    }

但它有效。 如果有人有更優雅的解決方案,我很想聽聽。

暫無
暫無

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

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