Reputation: 2294
I have a substring that contains commas. This substring lives inside of another string that is a semi colon delimited list. I need to match the commas in that substring. The substring has a key field "u3=" in front of it.
Example:
u1=something;u2=somethingelse;u3=cat,matt,bat,hat;u4=anotherthing;u5=yetanotherthing
Regex so far:
(?<=u3)(.*)(?=;)
The regex i've been working on above matches everything between "u3" and the last ";" in the outerstring. I need to match only the commas in the substring.
Any guidance would be greatly appreciated.
Upvotes: 0
Views: 366
Reputation: 48711
You didn't specify language!
C#, VB (.NET):
Using an infinite positive lookbehind,
(?<=u3=[^;]*),
Java:
Using a variable-length positive lookbehind:
(?<=u3=[^;]{0,9999}),
PHP (PCRE), Perl, Ruby:
Using \G
along with \K
token:
(?>u3=|\G(?!^))[^,;]+\K,
JavaScript:
Using two replace()
methods (if you are going to substitute),
var s = 'u1=something;u2=somethingelse;u3=cat,matt,bat,hat;u4=anotherthing;u5=yetanotherthing';
console.log(
s.replace(/u3=[^;]+/, function(match) {
return match.replace(/,/g, '*');
})
)
Upvotes: 1
Reputation: 5043
If this was PHP I would do this:
<?php
$str = 'u1=something;u2=somethingelse;u3=cat,matt,bat,hat;u4=anotherthing;u5=yetanotherthing;';
$split = explode(';', $str);
foreach ($split as $key => $value) {
$subsplit = explode('=',$value);
if ($subsplit[0] == 'u3') {
echo $subsplit[1];
preg_match_all('/,/', $subsplit[1], $matches, PREG_OFFSET_CAPTURE);
}
}
var_dump($matches);
Upvotes: 0
Reputation: 14179
Try to use this regex:
(?<=u3)[^;]+
The result is:
=cat,matt,bat,hat
Upvotes: 0