Jamie Marshall
Jamie Marshall

Reputation: 2294

Find all commas between two seperate characters in string

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

Answers (3)

revo
revo

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,

Live demo

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

geoidesic
geoidesic

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

Michele Pisani
Michele Pisani

Reputation: 14179

Try to use this regex:

(?<=u3)[^;]+

The result is:

=cat,matt,bat,hat

Upvotes: 0

Related Questions