Java regex content between single quotes

后端 未结 5 1391
臣服心动
臣服心动 2020-12-09 10:37

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:

5条回答
  •  有刺的猬
    2020-12-09 11:03

    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");
                }
            } 
        }
    }
    

提交回复
热议问题