2016-12-08 40 views
-6

請參閱我正在尋找一個正則表達式代碼,其中文本字段只應接受這些[javascript] - 輸入文本字段的正則代碼不允許以0開頭,但允許爲0並且不應該允許字符+, - ,

  1. 只有正整數
  2. 可以讓0
  3. 不應該允許+, - ,.

它不應該匹配:0345,7.,7 +,7,0.7,-7,7-,..7

它不能接受: 1. + 2。 - 3.。

注:我不想按鍵的功能,我正在尋找的正則表達式

+0

你的意思是'+'''-'僅.'或包括'('和')'。 –

+0

它不應該接受+ - 。 –

回答

1

使用此:^(0|[1-9][0-9]*)$

演示:https://regex101.com/r/NaTDIO/1

+0

謝謝!但是如何排除我提到的其他3個字符呢? –

+0

他們不允許在這裏。你如何理解「不包括」? –

+0

我明白這一點,但它不適合我,這3個字符再次被接受。我不介意你是否複雜 –

0

這會不會是任何援助

$re = '/([1]\d+)/'; 
$str = '0123'; 

preg_match_all($re, $str, $matches); 

// Print the entire match result 
print_r($matches); 

的現在的JavaScript的等效

const regex = /([1]\d+)/g; 
const str = `0123`; 
let m; 

while ((m = regex.exec(str)) !== null) { 
    // This is necessary to avoid infinite loops with zero-width matches 
    if (m.index === regex.lastIndex) { 
     regex.lastIndex++; 
    } 

    // The result can be accessed through the `m`-variable. 
    m.forEach((match, groupIndex) => { 
     console.log(`Found match, group ${groupIndex}: ${match}`); 
    }); 
} 
+0

這是一個JavaScript問題。 – vlaz

+0

謝謝,但我正在尋找一個正則表達式。 –

+0

您的代碼只是搜索匹配項,它不會測試整個字符串是否匹配。所以它會允許在兩者之間不匹配的字符串。我也不明白你爲什麼擁有'[1]'。問題在哪裏說每個比賽中必須出現數字「1」? – Barmar

相關問題