Javascript Javascript正则表达式 - 拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4853118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex - split string
提问by WastedSpace
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
与正则表达式要求作斗争。我需要在找到正斜杠的任何地方将字符串拆分为数组。但如果正斜杠前面有转义符,则不会。
Eg, if I have this string:
例如,如果我有这个字符串:
hello/world
I would like it to be split into an array like so:
我希望它被拆分成一个数组,如下所示:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
如果我有这个字符串:
hello/wo\/rld
I would like it to be split into an array like so:
我希望它被拆分成一个数组,如下所示:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
有任何想法吗?
采纳答案by Tim Down
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementationby not using a regular expression.
以下内容有点冗长,但会起作用,并且通过不使用正则表达式避免了IE 的拆分实现中断的问题。
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\/foo/bar";
alert( splitPath(str).join(",") );
回答by Alan Moore
I wouldn't use split()
for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
我不会用split()
这个工作。匹配路径组件本身要容易得多,而不是分隔符。例如:
var subject = 'hello/wo\/rld';
var regex = /(?:[^\/\]+|\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
输出:
hello
wo\/rld
回答by T.J. Crowder
Here's a way adapted from the techniques in this blog post:
这是一种改编自这篇博文中的技术的方法:
var str = "Testing/one\/two\/three";
var result = str.replace(/(\)?\//g, function(Testing/one\/two\/three
, ){
return ? '/' : '[****]';
}).split('[****]');
Given:
鉴于:
[0]: Testing
[1]: one/two/three
The result is:
结果是:
var s='hello/wor\/ld';
s=s.match(/(([^\/]*(\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\/g,'')
/* returned value: (String)
hello
wor/ld
*/
That first uses the simple "fake" lookbehind to replace /
with [****]
and to replace \/
with /
, then splits on the [****]
value. (Obviously, replace [****]
with anything that won't be in the string.)
这首先使用简单的“假”回顾后,以取代/
与[****]
和更换\/
用/
,然后分裂的[****]
价值。(显然,替换[****]
为任何不在字符串中的内容。)
回答by kennebec
/* If you are getting your string from an ajax response or a data base query, that is, the string has not been interpreted by javascript, you can match character sequences that either have no slash or have escaped slashes. If you are defining the string in a script, escape the escapes and strip them after the match. */
/* 如果您从 ajax 响应或数据库查询中获取字符串,即该字符串尚未被 javascript 解释,您可以匹配没有斜杠或已转义斜杠的字符序列。如果您在脚本中定义字符串,请转义转义符并在匹配后去除它们。*/
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\(?:\\)*(?:[^\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
回答by Mike Samuel
For short code, you can use reverse to simulate negative lookbehind
对于短代码,您可以使用 reverse 来模拟负面的lookbehind
var str = "/hello/wo\/rld/";
var split = str.replace(/^\/|\?\/|\/$/g, function(match) {
if (match.indexOf('\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);
but to be efficient, it's probably better to split on /[/]/
and then walk the array and rejoin elements that have an escape at the end.
但为了高效,最好先拆分/[/]/
然后遍历数组并重新加入最后有转义符的元素。
回答by Hemlock
Something like this may take care of it for you.
像这样的事情可能会为您处理。
##代码##回答by Mikhail
Here's an example at rubular.com
这是rubular.com上的示例