簡體   English   中英

字符串不會使用正則表達式拆分

[英]String will not split using Regex

如代碼段所示,我有一個 Regex應該標識任何空行。 (我知道我可以只做 /n/n,但它不適合我的目的)。 我已經在文字編輯器中對其進行了測試,並且在使用查找工具時它會選取每一個新行。 但是在 JS 中,我仍然得到整個文件。 我在這里錯過了什么?

 const mockData = `This is some fake data with multiple sentences and line breaks`; const newArr = mockData.split(/^\\s*$/); console.log(newArr[0]);

您有一個多行字符串,但沒有使用m (多行)標志。 沒有它^$匹配整個字符串的開始/結束,所以只有當整個字符串由空格組成時,你才會拆分:

 //multiline - all whitespace const mockData = ` `; const newArr = mockData.split(/^\\s*$/); console.log(newArr);

使用m標志, ^$字符代替匹配每行的開始/結束。 所以現在正則表達式可以在空行或由換行符組成的行上拆分:

 const mockData = `This is some fake data with multiple sentences and line breaks`; const newArr = mockData.split(/^\\s*$/m); console.log(newArr);

如果您打算在換行符不留空格的空行處拆分,那么您可以完全避開^$字符,因為它們實際上更麻煩。 引擎可能會換行符之前進行拆分因為這是$行的結尾。 因此,與其嘗試使用更多正則表達式來解決這個問題,不如在空格 + 換行符或換行符 + 空格上拆分。

 const mockData = `This is some fake data with multiple sentences and line breaks`; const newArr = mockData.split(/\\s*[\\r\\n]+|[\\r\\n]+\\s*/); console.log(newArr);

有了這個,您就不需要使用多行標志,因為您從不使用它引入的行為。

另外,我應該注意到[\\r\\n]+對我來說是一個輕微的作弊。 行尾字符是\\r\\n或只是\\n ,您很可能永遠不會遇到簡單的\\r 然而,正確的正則表達式是\\r?\\n ,我覺得它很難看,特別是如果你試圖重復它 - (\\r?\\n)+ 字符類總是稍微不准確,但其方式永遠不會對准確性產生任何影響。

使用多行標志效果更好

const newArr = mockData.split(/\\s*$/m);

隨你挑

 const re1 = /^\\s*|\\s*$/m const re2 = /^\\s*$/m const re3 = /\\s*$/m const mockData = `This is some fake data with multiple sentences and line breaks`; const newArr1 = mockData.split(re1); console.log(JSON.stringify(newArr1)) const newArr2 = mockData.split(re2); console.log(JSON.stringify(newArr2)) const newArr3 = mockData.split(re3); console.log(JSON.stringify(newArr3))

暫無
暫無

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

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