开发者

match everything before and match everything after a certain character [duplicate]

开发者 https://www.devze.com 2023-01-06 19:12 出处:网络
This question already has answers here: 开发者_StackOverflow中文版 How do I split a string with multiple separators in JavaScript?
This question already has answers here: 开发者_StackOverflow中文版 How do I split a string with multiple separators in JavaScript? (25 answers) Closed 2 years ago.

I need one regex to match everything before and one to match everything after a certain character, like a colon.

 foo:bar

Something to match 'foo' and something to match 'bar'.


Don't use regexes for that. Use split.


In regex you are able to define groups (by parentheses).

"foo:bar".match(/(.*?):(.*)/) // -> ["foo:bar", "foo", "bar"]
//                               whole regexp, 1st group, 2nd group

.*? in first group means non-greedy version of .*, which prevents eating all of the string by it (matching as less as possible .'s)

(which really does not matter in this case, but matters when you'll be matching e.g. "foo:bar:spam")


You don't need regular expressions here.

var middle = str.indexOf(':');
var key = str.substr(0, middle);
var value = str.substr(middle + 1);

If you do want to use regular expressions, you can do it like this:

var matches = /([^:]+):(.+)/.exec(str);

var key = matches[1];
var value = matches[2];


These two should do it:

'foo:bar'.match(/(.*):/)
'foo:bar'.match(/:(.*)/)

Will there be more than one ":" in the string? If so, you'd probably prefer this one:

'foo:bar'.match(/(.*?):/)


If you want to use a regexp instead of str.split, you can use:

var str="foo:bar";
var pattern=/([^:]+):([^:]+)/gi;
var arr=pattern.exec(str);
arr.shift();

Now arr will be an array of two elements: ['foo', 'bar'].


You want look-ahead, and look-behind. Which match stuff followed by, or preceded by a certain character, without including that character in the match.

For look-ahead, you'd have something like .*(?=:) , which means any character, 0 or more times, followed by a colon, but don't include the colon in the match,

For look-behind, you have .*(?<=:) , which means any character 0 or more times, preceded by a colon, but don't include the colon in the match. The trick here is that the look-behind expression comes AFTER the rest, which can seem counter intuitive, because you're looking for a colon that comes before, but it's because any regex really returns a position, and you want the colon to come right before that position.

0

精彩评论

暂无评论...
验证码 换一张
取 消