简体   繁体   English

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

[英]Javascript won't split using regex

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. 我试图使用带有javascript函数拆分的前瞻性的正则表达式。 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? 有没有其他人认为匹配函数假设你有一个正则表达式,而split函数没有?

String.split accepts either a string or regular expression as its first parameter. String.split接受字符串或正则表达式作为其第一个参数。 The String.match method only accepts a regular expression. String.match方法只接受正则表达式。

I'd imagine that String.match will try and work with whatever is passed; 我想象String.match会尝试使用传递的任何东西; 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; String.split方法没有这样做的String.split ,因为它可以接受正则表达式和字符串; in this case it would be foolish to second-guess. 在这种情况下,猜测是愚蠢的。


Edit : (From: "JavaScript: The Definitive Guide") 编辑 :(来自:“JavaScript:权威指南”)

String.match requires a regular expression to work with. String.match需要使用正则表达式。 The passed argument needs to be a RegExp object that specifies the pattern to be matched. 传递的参数需要是一个RegExp对象,它指定要匹配的模式。 If this argument is not a RegExp , it is first converted to one by passing it to the RegExp() constructor. 如果此参数不是RegExp ,则首先通过将其传递给RegExp()构造函数将其转换为1。

如果我没记错(这里我可能会非常错误),在正则规则引擎广泛使用之前,split方法是在javascript中实现的,因此它可能是为了向后兼容。

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

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