I am trying to write a regex in Java to find the content between single quotes. Can one please help me with this? I tried the following but it doesn't work in some cases:
Pattern p = Pattern.compile("'([^']*)'");
Test Case: 'Tumblr' is an amazing app Expected output: Tumblr
Test Case: Tumblr is an amazing 'app' Expected output: app
Test Case: Tumblr is an 'amazing' app Expected output: amazing
Test Case: Tumblr is 'awesome' and 'amazing' Expected output: awesome, amazing
Test Case: Tumblr's users' are disappointed Expected output: NONE
Test Case: Tumblr's 'acquisition' complete but users' loyalty doubtful Expected output: acquisition
I appreciate any help with this.
Thanks.
This should do the trick:
(?:^|\s)'([^']*?)'(?:$|\s)
Example: http://www.regex101.com/r/hG5eE1
In Java (ideone):
import java.util.*;
import java.lang.*;
import java.util.regex.*;
class Main {
static final String[] testcases = new String[] {
"'Tumblr' is an amazing app",
"Tumblr is an amazing 'app'",
"Tumblr is an 'amazing' app",
"Tumblr is 'awesome' and 'amazing' ",
"Tumblr's users' are disappointed ",
"Tumblr's 'acquisition' complete but users' loyalty doubtful"
};
public static void main (String[] args) throws java.lang.Exception {
Pattern p = Pattern.compile("(?:^|\\s)'([^']*?)'(?:$|\\s)", Pattern.MULTILINE);
for (String arg : testcases) {
System.out.print("Input: "+arg+" -> Matches: ");
Matcher m = p.matcher(arg);
if (m.find()) {
System.out.print(m.group());
while (m.find()) System.out.print(", "+m.group());
System.out.println();
} else {
System.out.println("NONE");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With