单引号之间的Java正则表达式内容

单引号之间的Java正则表达式内容

本文介绍了单引号之间的Java正则表达式内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java编写一个正则表达式来查找单引号之间的内容。能帮我一个忙吗?我尝试了以下但在某些情况下它不起作用:

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. 测试用例:' Tumblr'是一个了不起的应用程序预期输出: Tumblr

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

测试用例: Tumblr是一个了不起的'应用'预期输出应用

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

测试用例:Tumblr是一个'惊人'应用预期输出:惊人

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

测试案例 Tumblr'太棒了'和'惊人'预期输出:真棒,令人惊叹

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

测试案例:Tumblr的用户感到失望预期输出:

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

测试案例:Tumblr的收购已完成,但用户的忠诚度令人怀疑预期产量收购

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

我感谢任何帮助。

谢谢。

推荐答案

这应该可以解决问题:

(?:^|\s)'([^']*?)'(?:$|\s)

示例:

在:

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

这篇关于单引号之间的Java正则表达式内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:56