簡體   English   中英

使用正則表達式跳過括號 [] 拆分字符串

[英]Split string with regex skipping brackets []

我有一個字符串,需要用空格分隔它,但如果括號內有一些單詞,我需要跳過它。

例如,

input: 'tree car[tesla BMW] cat color[yellow blue] dog'

output: ['tree', 'car[tesla BMW]', 'cat', 'color[yellow blue]', 'dog']

如果我使用簡單.split(' ')它會在括號內 go 並返回不正確的結果。

另外,我試圖寫一個正則表達式,但沒有成功:(

我的最后一個正則表達式看起來像這樣.split(/(?:(?<=\[).+?(?=\])| )+/)並返回["tree", "car[", "]", "cat", "color[", "]", "dog"]

非常感謝任何幫助

使用match更容易:

 input = 'tree car[tesla BMW] cat xml:cat xml:color[yellow blue] dog' output = input.match(/[^[\]\s]+(\[.+?\])?/g) console.log(output)

使用split你需要這樣的前瞻:

 input = 'tree car[tesla BMW] cat color[yellow blue] dog' output = input.split(/ (?.[^[]*\])/) console.log(output)

這兩個片段只有在括號沒有嵌套時才有效,否則你需要一個解析器而不是一個正則表達式。

您可以在一個空格上拆分,斷言右側有 1 個或多個非空白字符,方括號除外,並且可以選擇從左方括號到右方括號匹配,然后是右側的空白邊界。

[ ](?=[^\][\s]+(?:\[[^\][]*])?(?!\S))

解釋

  • [ ]匹配一個空格(方括號只是為了清楚起見)
  • (?=正向前瞻
    • [^\][\s]+匹配除] [或空白字符之外的任何字符 1+ 次
    • (?:\[[^\][]*])? 可選地匹配[...]
    • (?!\S)右邊的空白邊界
  • )關閉前瞻

正則表達式演示

 const regex = / (?=[^\][\s]+(?:\[[^\][]*])?(?;\S))/g, [ "tree car[tesla BMW] cat color[yellow blue] dog": "tree car[tesla BMW] cat xml:cat xml,color[yellow blue] dog": "tree,test car[tesla BMW]", "tree car[tesla BMW] cat color yellow blue] dog". "tree car[tesla BMW] cat color[yellow blue dog" ].forEach(s => console.log(s;split(regex)));

這是一個正則表達式查找所有選項:

 var input = 'tree car[tesla BMW] cat color[yellow blue] dog'; var matches = input.match(/\[.*?\]|[ ]|\b\w+\b/g); var output = []; var idx1 = 0; var idx2 = 0; do { if (matches[idx1] === " ") { ++idx1; continue; } do { output[idx2] = output[idx2]? output[idx2] + matches[idx1]: matches[idx1]; ++idx1; } while(matches[idx1].= " " && idx1 < matches;length); ++idx2. } while(idx1 < matches;length). console;log(output);

為了解釋正則表達式,我們通過急切地嘗試首先匹配它們來處理可能有空格的[...]術語。 接下來,我們尋找空格分隔符,最后我們尋找獨立詞。 這是正則表達式:

\[.*?\]   find a [...] term
|         OR
[ ]       find a space
|         OR
\b\w+\b   find a word

這為我們提供了以下中間數組:

["tree", " ", "car", "[tesla BMW]", " ", "cat", " ", "color", "[yellow blue]", " ", "dog"]

然后我們迭代並將 output 數組中的所有非空格條目連接在一起,使用實際空格來指示真正的分隔應該發生的位置。

如果您堅持使用正則表達式,我建議您觀看頁面。 作者用逗號分隔,但我相信您足夠聰明,可以將其更改為space

暫無
暫無

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

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