[英]Regex giving incorrect results
使用Java腳本嘗試使用正則表達式捕獲字符串中的數據。
我的字符串從左括號開始顯示為
['ABC']['ABC.5']['ABC.5.1']
我的目標是將正則表達式的每一部分作為一個塊或以數組的形式獲取。 我查看了一下,發現匹配功能可能是一個不錯的選擇。
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
我看到的輸出只是每個元素的[。
我希望數組像這樣
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
要獲得上述期望的輸出,正確的正則表達式和/或函數是什么?
您可以將此正則表達式與split一起使用:
\[[^\]]+
\\[
-匹配[
[^\\]]+
-匹配任何東西,除了]
一個或更多的時間 \\]
-匹配項]
let str = `['ABC']['ABC.5']['ABC.5.1']` let op = str.split(/(\\[[^\\]]+\\])/).filter(Boolean) console.log(op)
如果只想分離它們,則可以使用一個簡單的表達式,或者比分離它們更好的表達式:
\[\'(.+?)'\]
const regex = /\\[\\'(.+?)'\\]/gm; const str = `['ABC']['ABC.5']['ABC.5.1']`; const subst = `['$1']\\n`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.