Javascript 不会使用正则表达式进行分割
自从我开始写这个问题以来,我想我已经找到了每个问题的答案,但我想我还是会发布,因为它可能对其他人有用,而且更多的澄清可能会有所帮助。
我试图将正则表达式与 javascript 函数 split 一起使用。 由于某种原因,即使当我调用 match 时它找到了匹配项,它也没有拆分字符串。 我最初认为问题出在我的正则表达式中使用前瞻。 这是一个简化的示例:
不起作用:
"aaaaBaaaa".split("(?=B).");
起作用:
"aaaaBaaaa".match("(?=B).");
问题似乎是在拆分示例中,传递的字符串没有被解释为正则表达式。 使用正斜杠而不是引号似乎可以解决问题。
"aaaaBaaaa".split(/(?=B)./);
我用下面这个看起来很傻的例子证实了我的理论:
"aaaaaaaa(?=B).aaaaaaa".split("(?=B).");
有没有人认为 match 函数假设你有正则表达式而 split 函数没有,这很奇怪?
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.
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:
Doesn't work:
"aaaaBaaaa".split("(?=B).");
Works:
"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).");
Does anyone else think it's strange that the match function assumes you have a regular expression while the split function does not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
String.split
接受字符串或正则表达式作为其第一个参数。String.match
方法仅接受正则表达式。我想
String.match
将尝试处理传递的任何内容; 因此,如果您传递一个字符串,它会将其解释为正则表达式。String.split
方法无法做到这一点,因为它可以接受正则表达式和字符串; 在这种情况下,事后猜测是愚蠢的。编辑:(来自:“JavaScript:权威指南”)
String.match
需要使用正则表达式。 传递的参数必须是一个RegExp
对象,用于指定要匹配的模式。 如果此参数不是RegExp
,则首先通过将其传递给RegExp()
将其转换为一个构造函数。String.split
accepts either a string or regular expression as its first parameter. TheString.match
method only accepts a regular expression.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. TheString.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.Edit: (From: "JavaScript: The Definitive Guide")
String.match
requires a regular expression to work with. The passed argument needs to be aRegExp
object that specifies the pattern to be matched. If this argument is not aRegExp
, it is first converted to one by passing it to theRegExp()
constructor.如果我没记错的话(这里我可能是错的),在正则表达式引擎被广泛使用之前, split 方法是在 javascript 中实现的,所以它可能是为了向后兼容。
If I recall correctly (and I could be very wrong here), the split method was implemented in javascript before the regex engine was in wide use, so it's presumably for backward compatibility.