1
    String content = "$.test(\"I am do'in testing\") ";
    Matcher matcher = 
     Pattern.compile("\\$.test.*?(.*?[\"'](.*?)[\"'].*?)").matcher(content);

Output is ("I am do' but i need to capture I am do'in testing. Not sure ehat i am missing here ?

Similarly input can be "$.test(\'I am do"in testing\')" output should be I am do'in testing

scott miles
  • 1,511
  • 2
  • 21
  • 36

1 Answers1

1
\$.test.*?(.*?["'](.*?)["'].*?)

This is your regex. This regex is using lazy quantifier between ["'] and another ["']. This makes it match between " (double quote) and ' single quote when your input is: $.test("I am do'in testing")

Hence it matches and captures I am do in capture group #1.

Another problem is that you're not escaping dot after $ which may result in matching any character instead of literal dot.

You may use this regex to match string between both single or double quotes that skips escaped quotes with a backslash:

\$\.test[^'"]*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|'((?:[^'\\]*(?:\\.[^'\\]*)*))').*

RegEx Demo

Code:

final String regex = "\\$\\.test[^'\"]*(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'((?:[^'\\\\]*(?:\\\\.[^'\\\\]*)*))').*";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher( input );

while (matcher.find()) {
    System.out.printf("Group-1: %s, Group-2: %s%n", matcher.group(1), matcher.group(2));
}
anubhava
  • 761,203
  • 64
  • 569
  • 643