2

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') );

1
  • Another solution /#(.*) is ([^\(\)]*)/ (posted by someone who deleted, but I like it as well) Commented Mar 14, 2015 at 22:12

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Works great, except one thing -'#' is not captured, or i am missing something?
It's not inside any of captures group. Same as it was in the question. May be you need to include it to first group /(#.*) is (.*?)((|$)/m
just a tip: you can create NON-CAPTURE-groups which doesn't affect result but are for grouping like "(?: )"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.