Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex content between single quotes

Tags:

java

regex

quotes

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("'([^']*)'");
  1. Test Case: 'Tumblr' is an amazing app Expected output: Tumblr

  2. Test Case: Tumblr is an amazing 'app' Expected output: app

  3. Test Case: Tumblr is an 'amazing' app Expected output: amazing

  4. Test Case: Tumblr is 'awesome' and 'amazing' Expected output: awesome, amazing

  5. Test Case: Tumblr's users' are disappointed Expected output: NONE

  6. Test Case: Tumblr's 'acquisition' complete but users' loyalty doubtful Expected output: acquisition

I appreciate any help with this.

Thanks.

like image 930
user1744332 Avatar asked May 25 '13 04:05

user1744332


1 Answers

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");
            }
        } 
    }
}
like image 185
guido Avatar answered Oct 04 '22 22:10

guido