简体   繁体   English

正则表达式与特殊字符元字符匹配

[英]regex matching with special characters metacharacters

I am trying to match certain strings and while I have to escape some special characters it still isn't matching correctly. 我正在尝试匹配某些字符串,尽管我必须转义一些特殊字符,但仍然无法正确匹配。

I have this 我有这个

 var first=/.+?(?=\[)/i

which still matches the whole string which needs to only match up to the first [ 仍然匹配整个字符串,只需要匹配第一个[

this is the string business[account] 这是字符串业务[帐户]

I need to match business then match account as well. 我需要匹配业务然后匹配帐户。 It is for a plugin that be used to get the object notations with these later. 它是用于以后用于获取对象符号的插件的。 Every element has a different attribute. 每个元素都有一个不同的属性。

For something this simple, a lookahead isn't really necessary. 对于这种简单的事情,实际上并不需要提前进行。 Try using a character class like this: 尝试使用以下字符类:

var first = /[^[]+/

This will match one or more of any character other than [ . 这将匹配[ 以外的任何一个或多个字符。

If you'd like to work this into a regex that can match both parts of a string like "business[account]" , try this: 如果您想将其处理为可以匹配字符串两个部分(例如"business[account]"的正则表达式,请尝试以下操作:

/([^[]+)\[([^\]]+)\]/

This will match one or more of any character other than [ , captured in group 1, followed by a [ , followed by one or more of any character other than ] , captured in group 2, followed by ] . 这将匹配在组1中捕获的[ 以外的任何一个或多个字符,然后是[ ,然后是在组2中捕获的] 以外的任何一个或多个字符,然后是]

Eg 例如

console.log(/([^[]+)\[([^\]]+)\]/.exec("business[account]"));
// ["business[account]", "business", "account"]

You're almost there; 你快到了; just add groups (with parentheses) to match what you want: 只需添加组(带括号)以匹配您想要的内容即可:

var m = /(.+?)\[(.+?)\]/.exec("business[account]");
console.log("variable: " + m[1], "index: " + m[2]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM