簡體   English   中英

使用正則表達式從字符串中刪除不需要的字符組

[英]remove unwanted groups of characters from string using regex

鑒於: 1999 some text here 1.3i [more]
需要: some text here

以下正則表達式-replace replace(/[\\d{4} |\\d\\.*$]/,'') -失敗,它只刪除了第一位數字。 知道為什么以及如何解決它嗎?

 var s = "1999 some text here 1.3i [more]" console.log(s.replace(/[\\d{4} |\\d\\.*$]/,'')) 

您擁有的正則表達式僅刪除第一個數字,因為它僅匹配1個字符-一個數字, {4} ,空格, | . *$ (如[...]形成一個字符類 ),只有一次(有沒有全球性的修改)。

您可以使用

/^\d{4}\s+|\s*\d\..*$/g

正則表達式演示

基本上,刪除構成字符類的[] ,添加g修飾符以執行多次替換,最后添加.* (任何字符匹配模式)。

詳細資料

第一種選擇:
- ^ -字符串開頭
- \\d{4} -4位數字
- \\s+ -1+空格

第二種選擇:
- \\s* -0+空格
- \\d一個數字
- \\. -一個點
- .* -最多0個字符,最多...
- $ -字符串的結尾

 var rx = /^\\d{4}\\s+|\\s*\\d\\..*$/g; var str = "1999 some text here 1.3i [more]"; console.log(str.replace(rx, '')); 

暫無
暫無

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

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