laggingreflex
laggingreflex

Reputation: 34627

Regex: Exclude capturing a pattern which may or may not be present

I have a few variations of similar strings:

#This is a string
#This is another string (with some info in parentheses)

I want to run them all through a Regex and capture "#This" in the first capture group, and "a string" or "another string" in the second capture group.

Notice in the second string I don't want the parentheses' or its content.

I've tried a bunch or Regexes that give the following outputs

/#(.*) is (.*)/: simplest regex, but doesn't exclude the parentheses and its contents

String1 Match1:     This
String1 Match2:     a string
String2 Match1:     This
String2 Match2:     another string (with some info in parentheses)

/#(.*) is (.*)\(/ adding an opening parentheses works only for string that actually has it

String1 Match1:     null
String1 Match2:     null
String2 Match1:     This
String2 Match2:     another string

/#(.*) is (.*)\(*/ making it optional with a * (this is incorrect I guess)

String1 Match1:     This
String1 Match2:     a string
String2 Match1:     This
String2 Match2:     another string (with some info in parentheses)

/#(.*) is (.*)\(?/ making it optional with a ? (same result)

String1 Match1:     This
String1 Match2:     a string
String2 Match1:     This
String2 Match2:     another string (with some info in parentheses)

/#(.*) is (.*?)\(*/ making it non-greedy

String1 Match1:     This
String1 Match2:     null
String2 Match1:     This
String2 Match2:     null

var string1 = "#This is a string";
var string2 = "#This is another string (with some info in parentheses)";

// var regex = /#(.*) is (.*)/;
// var regex = /#(.*) is (.*)\(/;
// var regex = /#(.*) is (.*)\(*/;
   var regex = /#(.*) is (.*)\(?/;
// var regex = /#(.*) is (.*?)\(*/;

var match1 = string1.match(regex);
var match2 = string2.match(regex);

alert('String1 Match1: \t' + ((match1&&match1[1])?match1[1]:'null') + '\nString1 Match2: \t' + ((match1&&match1[2])?match1[2]:'null') +
    '\nString2 Match1: \t' + ((match2&&match2[1])?match2[1]:'null') + '\nString2 Match2: \t' + ((match2&&match2[2])?match2[2]:'null') );

Upvotes: 2

Views: 261

Answers (1)

SeriousDron
SeriousDron

Reputation: 1346

To make any symbol or group (including) opening parentheses optional you need to use ? (question mark), not * (star). You need to stop on ( or end of line which come first so maybe You need somethink like /#(.*) is (.*?)(\(|$)/m

Upvotes: 2

Related Questions