![](/img/trans.png)
[英]Javascript RegEx extract all words as single matches but not numbers from a string
[英]Regex to extract two numbers with spaces from string
我有簡單的雷克薩斯問題。 我有示例字符串,如:
Something1\sth2\n649 sth\n670 sth x
Sth1\n\something2\n42 036 sth\n42 896 sth y
我想從字符串中提取這些數字。 所以從第一個例子我需要兩組: 649
和670
。 從第二個例子: 42 036
和42 896
。 Then I will remove space
。
目前我有這樣的事情:
\d+ ?\d+
但這不是一個好的解決方案。
您可以使用
\n\d+(?: \d+)?
\\n
- 匹配新行\\d+
- 一次或多次匹配從 0 到 9 的數字(?: \\d+)?
- 匹配空格后跟數字一次或多次。 ( ? 使它成為可選的) let strs = ["Something1\\sth2\\n649 sth\\n670 sth x","Sth1\\n\\something2\\n42 036 sth\\n42 896 sth y"] let extractNumbers = str => { return str.match(/\\n\\d+(?: \\d+)?/g).map(m => m.replace(/\\s+/g,'')) } strs.forEach(str=> console.log(extractNumbers(str)))
如果您需要刪除空格。 那么最簡單的方法是刪除空格,然后使用 2 個不同的正則表達式刮取數字。
str.replace(/\s+/, '').match(/\\n(\d+)/g)
首先,您使用帶有+
量詞的\\s
標記使用replace
刪除空格。
然后您使用\\\\n(\\d+)
捕獲數字。
正則表達式的第一部分,幫助我們確保我們不會捕獲沒有關注一個新的行號,使用\\
逃脫\\
從\\n
。
第二部分(\\d+)
是實際的匹配組。
var str1 = "Something1\\sth2\\n649 sth\\n670 sth x"; var str2 = "Sth1\\n\\something2\\n42 036 sth\\n42 896 sth y"; var reg = /(?<=\\n)(\\d+)(?: (\\d+))?/g; var d; while(d = reg.exec(str1)){ console.log(d[2] ? d[1]+d[2] : d[1]); } console.log("****************************"); while(d = reg.exec(str2)){ console.log(d[2] ? d[1]+d[2] : d[1]); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.