Javascript 不会使用正则表达式拆分 [英] Javascript won't split using regex

查看:24
本文介绍了Javascript 不会使用正则表达式拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始写这个问题以来,我想我已经找到了我遇到的每个问题的答案,但我想我还是会发帖,因为它可能对其他人有用,更多的澄清可能会有所帮助.

Since I started writing this question, I think I figured out the answers to every question I had, but I thought I'd post anyway, as it might be useful to others and more clarification might be helpful.

我试图将正则表达式与 javascript 函数 split 一起使用.出于某种原因,即使在我调用 match 时找到匹配项,它也没有拆分字符串.我最初认为问题是在我的正则表达式中使用了前瞻.这是一个简化的例子:

I was trying to use a regular expression with lookahead with the javascript function split. For some reason it was not splitting the string even though it finds a match when I call match. I originally thought the problem was from using lookahead in my regular expression. Here is a simplified example:

不起作用:

"aaaaBaaaa".split("(?=B).");

作品:

"aaaaBaaaa".match("(?=B).");

问题似乎是在拆分示例中,传递的字符串没有被解释为正则表达式.使用正斜杠代替引号似乎可以解决问题.

It appears the problem was that in the split example, the passed string wasn't being interpreted as a regular expression. Using forward slashes instead of quotes seems to fix the problem.

"aaaaBaaaa".split(/(?=B)./);

我用下面看起来很傻的例子证实了我的理论:

I confirmed my theory with the following silly looking example:

"aaaaaaaa(?=B).aaaaaaa".split("(?=B).");

有没有人认为 match 函数假设您有正则表达式而 split 函数没有,这很奇怪吗?

Does anyone else think it's strange that the match function assumes you have a regular expression while the split function does not?

推荐答案

String.split 接受字符串或正则表达式作为其第一个参数.String.match 方法只接受正则表达式.

String.split accepts either a string or regular expression as its first parameter. The String.match method only accepts a regular expression.

我认为 String.match 会尝试处理传递的任何内容;因此,如果您传递一个字符串,它会将其解释为正则表达式.String.split 方法没有这样做,因为它可以接受正则表达式和字符串;在这种情况下,再猜测是愚蠢的.

I'd imagine that String.match will try and work with whatever is passed; so if you pass a string it will interpret it as a regular expression. The String.split method doesn't have the luxury of doing this because it can accept regular expressions AND strings; in this case it would be foolish to second-guess.

编辑:(来自:JavaScript:权威指南")

Edit: (From: "JavaScript: The Definitive Guide")

String.match 需要使用正则表达式.传递的参数需要是一个 RegExp 对象,用于指定要匹配的模式.如果此参数不是 RegExp,则首先通过将其传递给 RegExp() 将其转换为 1构造函数.

String.match requires a regular expression to work with. The passed argument needs to be a RegExp object that specifies the pattern to be matched. If this argument is not a RegExp, it is first converted to one by passing it to the RegExp() constructor.

这篇关于Javascript 不会使用正则表达式拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆