簡體   English   中英

如何在JavaScript中使用正則表達式匹配並返回零?

[英]How do I match and return a zero with a regular expression in javascript?

我正在嘗試從字符串中提取數字。 該數字可能為零。 數字顯示如下:“ + 123”,“-8”或“ 0”。

alert( '+123'.match(/[-?|+?]\d+/) );
alerts +123

alert( '-8'.match(/[-?|+?]\d+/) );
alerts -8

alert( '0'.match(/[-?|+?]\d+/) );
alerts null // why oh why?

如何獲得'0'.match(/ [-?| +?] \\ d + /)返回0而不是null?

模式

[-?|+?]

將精確匹配一個-+| 還是? 你想要的是

[-+]?

它將匹配-+一或零次。

這也將允許數字“ 123”通過。 如果需要+號,請使用以下命令:

/0|[-+][1-9]\d*/

這里

var rePattern = /[+-]?\d+/;

"0".match(rePattern) // 0
"+44".match(rePattern) //+44
"-3".match(rePattern) //-3

請注意,這不像肯尼的嚴格

暫無
暫無

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

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