Reputation: 51
For example, how can I select the segment of this phrase:
49up_88x126x476mm_3mm gutters_28375x40_Ft First_Rollem_sw
between the 2nd and 3rd "_" or between the 2nd and 4th, etc.?
Upvotes: 0
Views: 40
Reputation: 29647
This can be done without regex.
Just split on the underscore.
Then take the elements you need from the resulting array.
And join the elements you want back together.
Javascript example:
var str = '49up_88x126x476mm_3mm gutters_28375x40_Ft First_Rollem_sw';
console.log(str);
var arr = str.split('_');
var str_2_3 = arr.slice(2-1,3).join('_'); //2-1, because index starts at 0
console.log(str_2_3);
var str_2_4 = arr.slice(2-1,4).join('_');
console.log(str_2_4);
Upvotes: 1
Reputation:
Not that easy but, this is one way.
Basic regex ^(?:[^_]*_){A}([^_]*(?:_[^_]*){B})_
Where
A < B
A = From Number
B = To Number - From Number - 1
Capture group 1 contains the between contents.
For example, 2 to 4 would be
A = 2
B = 4 - 2 - 1 = 1
The regex is ^(?:[^_]*_){2}([^_]*(?:_[^_]*){1})_
Output
** Grp 0 - ( pos 0 : len 39 )
49up_88x126x476mm_3mm gutters_28375x40_
** Grp 1 - ( pos 18 : len 20 )
3mm gutters_28375x40
Readable regex
^
(?:
[^_]*
_ # From = 2
){2}
( # (1 start)
[^_]*
(?:
_
[^_]*
){1}
) # (1 end)
_ # To = 4
Upvotes: 1