regular expression to match delimited substrings
I have a string something like this
var test = 'Hello you have multiple L2:Me here;L3:Me not here; 开发者_StackOverflow中文版and some other text...';
I want to get string array
L2:Me here
L3:Me not here
The format is L(some number):text;
What will be regex?
If those semicolons are always going to be there, you can use something like this:
var re = /L[0-9]+:[^;]+/g;
var test = 'Hello you have multiple L2:Me here;L3:Me not here; and some other text...';
var match = test.match(re);
console.log(match);
// match = ["L2:Me here", "L3:Me not here"]
Explanation:
L[0-9]+:
matches L followed by any sequence of numbers, followed by a colon (i.e."L105:"
)[^;]+
matches any character that's not a semicolon (the[^;]
part) at least once (the+
part), and only stops once it reaches a semicolon- The
g
flag makes the matches global, that is, to not just find the first match and stop
I have not tested this but it should work
/(L\d:[a-zA-Z0-9\s]+;)/
The regex is:
/L\d+:[^;]*/g
Meaning, begin with an L
, followed by a sequence of one or more digits (\d+
), a :
, and a sequence of zero or more characters not including a ;
([^;]*
). The g
on the end is for "global", and makes the regex apply to more than one occurence.
Use with match:
var parts = test.match(/L\d+:[^;]*/g);
精彩评论