[英]JS Regex for matching specific array increment ignoring string and seperate increment
I have the following input fields with name attributes of: 我具有名称属性为的以下输入字段:
carousels['components'][0][0][title]
carousels['components'][0][1][title]
carousels['components'][0][2][title]
carousels['components'][1][0][title]
carousels['components'][1][1][title]
carousels['components'][1][2][title]
carousels['components'][2][0][title]
carousels['components'][2][1][title]
carousels['components'][2][2][title]
I am trying to match the final [ number ] eg this part: 我试图匹配最终的[数字]例如这部分:
carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]
While ignoring the rest 而忽略其余
Here is my regex pattern: 这是我的正则表达式模式:
/(\[[^components\]])+(\[*])/
This affects both of the int's within brackets when I just want the last one. 当我只想要最后一个时,这会影响括号内的两个int。 This regex also doesn't recognize the specific requirement of the first array key 'component' 此正则表达式也无法识别第一个数组键“ component”的特定要求
Live regex test here: 实时正则表达式测试在这里:
http://www.regexpal.com/?fam=94974 http://www.regexpal.com/?fam=94974
You can try this 你可以试试这个
^.*(\[.*?\])\[.*?\]$
<------->
Match in this(1st captured group)
If you want to match ['components']
exclusively, then you can use 如果您想专门匹配['components']
,则可以使用
^.*\['components'\].*(\[.*?\])\[.*?\]$
If you want to get the last [
+ digits
+ ]
, you can use 如果要获取最后的 [
+ digits
+ ]
,可以使用
/^.*\[(\d+)\].*$/
See the regex demo 见正则表达式演示
Backtracking will help getting exactly the last occurrence of [digits]
. 回溯将有助于准确获得[digits]
的最后一次出现。 Grab Group 1 value. 抓取组1的值。
var re = /^.*\\[(\\d+)\\].*$/; var str = 'carousels[\\'components\\'][0][0][title]\\ncarousels[\\'components\\'][0][1][title]\\ncarousels[\\'components\\'][0][2][title]\\n\\ncarousels[\\'components\\'][1][0][title]\\ncarousels[\\'components\\'][1][1][title]\\ncarousels[\\'components\\'][1][2][title]\\n\\ncarousels[\\'components\\'][2][0][title]\\ncarousels[\\'components\\'][2][1][title]\\ncarousels[\\'components\\'][2][2][title]'; for (var s of str.split("\\n")) { var res = (m=re.exec(s)) ? m[1] : ""; if (res) { document.body.innerHTML += s + ": " + res + "<br/>"; } }
UPDATE : 更新 :
To get the first [
+ digits
+ ]
, you need to use lazy matching with the first dot: 要获得第一个 [
+ digits
+ ]
,您需要对第一个点使用惰性匹配:
/^.*?\[(\d+)\].*$/
^ - Here, the ? will make matching lazy/reluctant
(it will match any 0+ chars other than a newline as few as possible)
See another regex demo . 参见另一个正则表达式演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.