情况如下:
var stringExample = "hello=goodbye==hello";
var parts = stringExample.split("=");
输出:
hello,goodbye,,hello
我需要这个输出:
hello,goodbye==hello
连续/重复的字符必须忽略,只取单个"="
来拆分。
也许一些正则表达式?
情况如下:
var stringExample = "hello=goodbye==hello";
var parts = stringExample.split("=");
输出:
hello,goodbye,,hello
我需要这个输出:
hello,goodbye==hello
连续/重复的字符必须忽略,只取单个"="
来拆分。
也许一些正则表达式?
您可以使用正则表达式:
var parts = stringExample.split(/\b=\b/);
\b
检查单词边界。
Most probably, @dystroys answer is the one you're looking for. But if any characters other than alphanumerics (A-Z
, a-z
, 0-9
or _
) could surround a "splitting =
"), then his solution won't work. For example, the string
It's=risqué=to=use =Unicode!=See?
would be split into
"It's", "risqué=to", "use Unicode!=See?"
So if you need to avoid that, you would normally use a lookbehind assertion:
result = subject.split(/(?<!=)=(?!=)/); // but that doesn't work in JavaScript!
So even though this would only split on single =
s, you can't use it because JavaScript doesn't support the (?<!...)
lookbehind assertion.
Fortunately, you can always transform a split()
operation into a global match()
operation by matching everything that's allowed between delimiters:
result = subject.match(/(?:={2,}|[^=])*/g);
will give you
"It's", "risqué", "to", "use ", "Unicode!", "See?"
作为可能的解决方案的第一个近似值可能是:
".*[^=]=[^=].*"
请注意,这只是正则表达式,如果您想将它与 egrep、sed、java 正则表达式或其他任何东西一起使用,请注意是否需要转义某些内容。
注意!:这是第一个近似值,可以改进。请注意,例如,此正则表达式不会匹配此字符串“=”(null - equal - null)。