3

The pattern below allows me to isolate a single term that is enclosed in double quotes. However i'd like to be able to isolate multiple terms that are double quoted and separate them if possible.

pattern MyPattern = pattern.compile('("(.*)")');

Matcher MyMatcher = MyPattern.matcher('asf "dfa, sfdsf  sdfasdf asfdasdf sdf asf , asdfs ,  asf sf" sf as"emily, md " dfa  ');
System.debug('THE STATEMENT MATCHES: ' + MyMatcher.find());
System.debug('THE MATCH FROM EXPRESSION: ' + MyMatcher.group());

The pattern above isolates the following string:

Isolated String: "dfa, sfdsf  sdfasdf asfdasdf sdf asf , asdfs ,  asf sf" sf as"emily, md "

However ideally i'd like to have the following isolated strings:

Match 1: "dfa, sfdsf  sdfasdf asfdasdf sdf asf , asdfs ,  asf sf"
Match 2: "emily, md "
3

You can use generate a List<String> to store results using a while loop. Also, change your pattern to ("[^"]*"). The following worked for me in Execute Anonymous:

static final Pattern doubleQuoteWrapped = Pattern.compile('("[^"]*")');
static List<String> parse(String input)
{
    Matcher m = doubleQuoteWrapped.matcher(input);
    List<String> output = new List<String>();
    while (m.find()) output.add(m.group());
    return output;
}

String input = '"dfa, sfdsf  sdfasdf asfdasdf sdf asf , asdfs ,  asf sf" sf as"emily, md "';
system.debug(parse(input));

Output:

[11]|DEBUG|("dfa, sfdsf sdfasdf asfdasdf sdf asf , asdfs , asf sf", "emily, md ")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.