Java regex content between single quotes

六月ゝ 毕业季﹏ 提交于 2019-11-28 23:33:29

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 don't allow the single quote character, ', or the space character, ' ', to be in the pattern, then you're good to go. I used + because I assumed you don't want an empty entry (if not, change it back to an *):

Pattern p = Pattern.compile("'([^' ]+)'");

Try the next:

'\w+'|'\w+(\s\w+)*'

Try this simple regex pattern:

'([^\s']+)'

and a test code:

try {
    Pattern regex = Pattern.compile("'([^\\s']+)'");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        for (int i = 1; i <= regexMatcher.groupCount(); i++) {
            // matched text: regexMatcher.group(i)
            // match start: regexMatcher.start(i)
            // match end: regexMatcher.end(i)
        }
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

Just don't let ' ' appear in the output. Use this regex:

'([^' ]*)'

Or make sure the quote pair is wrapped by spaces.

(?:^| )'([^']*)'(?: |$)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!