sojim2
sojim2

Reputation: 1307

Regex: How would I get everything after a string?

(Solved - It's currently not possible with Javascript Regex to exclude part of a selected string as of this posting date)

Searched around and couldn't find a clear example for this case.

Currently I have this text block:

Characteristics
Content: 100% Polyurethane
Backing: Polyester
Weight: 20 oz/ly (620 gr/lm)
Width: 54" (137cm)
Bolt Size: 35 yards (32 m)
Maintenance: W/B-Clean w

I'd like to extract any text after Content: (note the space)

So that it extracts 100% Polyurethane

Currently I have this - (But it includes Content:): http://regexr.com/3dbct

My purpose is to have a regex command that can later extract anything after Width:, Backing:, etc.

Edit: Requirement is we can't use any javascript, only regex

Upvotes: 0

Views: 2605

Answers (2)

James Buck
James Buck

Reputation: 1640

(?:Content|Backing|Width):\s*(.*$)

Demo here.

There's no way to exclude the bit before the : because of JavaScript regex limitations but you could just capture the content matched in capturing group 1.

Upvotes: 1

forgivenson
forgivenson

Reputation: 4435

Your example works, you just need to grab the value of the capture group (what you have in parentheses).

Note: the m flag in the regex means:

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

Also, the exec method returns an array (or null if there is no match). The first item in the array, index 0, is the full match, and each index after that is each capture group, in order. So, index 1 is the first capture group, which is what you want in this case.

Update: I made it more generic. Now it loops through an array of data labels, and grabs the text after each of them.

var dataLabels = ['Content','Backing','Weight','Width','Bolt Size','Maintenance'];

var input = 'Characteristics\nContent: 100% Polyurethane\nBacking: Polyester\nWeight: 20 oz/ly (620 gr/lm)\nWidth: 54" (137cm)\nBolt Size: 35 yards (32 m)\nMaintenance: W/B-Clean w';

var regex, i, match;

for(i = 0; i < dataLabels.length; i++) {
    regex = new RegExp(dataLabels[i] + ': (.*)', 'm');

    match = regex.exec(input);

    if(match !== null) {
        // do something with this
        console.log(dataLabels[i] + ' = ' + match[1]);
    }
}

Upvotes: 0

Related Questions