iYeager
iYeager

Reputation: 57

Regex: Split on underscore, sometimes

I have a string that can read either this format:

Static_1264_1264_11232013_1234

or this format:

Static_1264__11232013_1234

Note the second example has only one instance of '1264' and where the second one should be there are still pre and post-underscores. When I was guaranteed a value there I used this regex to split the string into variables I passed elsewhere:

([^_]+)_([^_]+)_([^_]+)_([^_]+)_([^/]+)

But that doesn't see a match when the second number is missing. I tried adding the non-greedy value to the second piece, like so:

([^_]+)_([^_]+)_([^_]+?)_([^_]+)_([^/]+)

But that didn't help either.

Upvotes: 1

Views: 8503

Answers (2)

mzedeler
mzedeler

Reputation: 4369

Why not just use

var str = 'Static_1264__1264_11232013_1234';
str.match(/([^_]+)/g);

Output:

["Static", "1264", "1264", "11232013", "1234"]

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208475

+ means "match the previous element one or more times". If you want something to be optional, use a * instead which means "match the previous element zero or more times":

([^_]+)_([^_]+)_([^_]*)_([^_]+)_([^/]+)

Upvotes: 3

Related Questions