Java regular expression content between single quotes
I try to write a regular expression in Java to find the contents between single quotes Can someone help me? I've tried the following, but it doesn't work in some cases:
Pattern p = Pattern.compile("'([^']*)'");
>Test case: 'Tumblr' is an amazing application expected output: Tumblr > test case: Tumblr is an amazing "application" expected output: Application > test case: Tumblr is an "amazing" application expected output: Amazing > test case: Tumblr is "great" and "amazing" expected output: great, Amazing > test case: users of Tumblr are disappointed. Expected output: none > test case: Tumblr's "acquisition" is completed, but users' loyalty doubts the expected output: acquisition
I appreciate any help
thank you.
Solution
This should be the trick:
(?:^|\s)'([^']*?)'(?:$|\s)
Example: http://www.regex101.com/r/hG5eE1
Java (ideone) year:
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"); } } } }