Javascript不会使用正则表达式进行拆分

Javascript不会使用正则表达式进行拆分

本文介绍了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.

我试图使用带有ja函数拆分的前瞻的正则表达式。由于某种原因,即使在我调用匹配时找到匹配项,它也不会拆分字符串。我原本以为问题来自于我的正则表达式中使用前瞻。这是一个简化的例子:

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).");

有没有人认为匹配函数假设你有一个正则表达式而分裂函数确实很奇怪不是吗?

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 方法无法做到这一点,因为它可以接受正则表达式AND字符串;在这种情况下,猜测是愚蠢的。

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:The Definitive Guide)

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

String.match 需要正则表达式跟...共事。传递的参数必须是 RegExp 对象,该对象指定要匹配的模式。如果此参数不是 RegExp ,则首先将其转换为 RegExp( ) 构造函数。

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不会使用正则表达式进行拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:43