[英]Regular Expression match in javascript
I have the string SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])
and I need to get the elements [A2:A10],[B2:B10],[C2:C10],[D2:D10]
in an array, so I used match()
in js.我有字符串SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])
并且我需要获取元素[A2:A10],[B2:B10],[C2:C10],[D2:D10]
在一个数组中,所以我在js中使用了match()
。 The code snippet is代码片段是
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[(a-zA-Z0-9)+\]/;
matches = formula.match(reg);
But I am not getting the match.但我没有得到比赛。 I hope the regular expression is wrong.我希望正则表达式是错误的。 I am very poor in building regular expression.我在构建正则表达式方面很差。 What will be the correct regular expression?什么是正确的正则表达式?
Try it like this:像这样尝试:
var formula = 'SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])';
var reg = /\[\w+:\w+\]/g;
matches = formula.match(reg);
Output:输出:
["[A2:A10]", "[B2:B10]", "[C2:C10]", "[D2:D10]"]
Your regex was in the right direction, but didn't include the colon and captured individual characters.您的正则表达式方向正确,但不包括冒号和捕获的单个字符。 The \\w
escape sequence I used is a shortcut for a word character ( [a-zA-Z0-9_]
), makes it more readable.我使用的\\w
转义序列是单词字符( [a-zA-Z0-9_]
)的快捷方式,使其更具可读性。 The g
flag is necessary to get all matches instead of just the first one. g
标志是获取所有匹配项所必需的,而不仅仅是第一个匹配项。
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[.*?\]/g;
matches = formula.match(reg);
var str = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var matches = str.match(/\[[A-Z0-9:]+\]/g);
alert(matches);
Note, you use the g
flag on the regex to get all the matches.请注意,您使用正则表达式上的g
标志来获取所有匹配项。
You can see it working here: http://jsfiddle.net/jfriend00/aTrLU/你可以在这里看到它的工作: http : //jsfiddle.net/jfriend00/aTrLU/
The regex you need is您需要的正则表达式是
/\[[A-Z][0-9]+:[A-Z][0-9]+\]/gi
The g modifier indicates that we should do a global mtching and return all the results, not just the first g 修饰符表示我们应该进行全局匹配并返回所有结果,而不仅仅是第一个
The i modifier indicates that we need a case-insensitive matching i 修饰符表示我们需要不区分大小写的匹配
An assumption made is that you don't want to include [E2:E10:], because of extra semicolon所做的假设是您不想包含 [E2:E10:],因为有额外的分号
Your regexp doesn't include the colon :
.您的正则表达式不包括冒号:
。
Try this: /\\[([0-9A-Z:]+)\\]/
, in particular why I have quoted and unquoted square brackets there.试试这个: /\\[([0-9A-Z:]+)\\]/
,特别是为什么我在那里引用和未引用的方括号。
Plus, your input string isn't quoted.另外,您的输入字符串没有被引用。
I believe you forgot the quotes.我相信你忘记了引号。 Also, what you need is also the global flag.此外,您还需要全局标志。 Here the code:这里的代码:
var formula = "SUM([A2:A10],[B2:B10],[C2:C10],[D2:D10])";
var reg = /\[[0-z]+:[0-z]+\]/g;
var matches = formula.match(reg);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.