【问题标题】:Extract a substring between double quotes with regular expression in Java在Java中用正则表达式提取双引号之间的子字符串
【发布时间】:2013-01-29 02:28:04
【问题描述】:

我有一个这样的字符串:

"   @Test(groups = {G1}, description = "adc, def")"

我想在Java中使用正则表达式提取“adc,def”(不带引号),我该怎么做?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    如果你真的想使用正则表达式:

    Pattern p = Pattern.compile(".*\\\"(.*)\\\".*");
    Matcher m = p.matcher("your \"string\" here");
    System.out.println(m.group(1));
    

    解释:

    .*   - anything
    \\\" - quote (escaped)
    (.*) - anything (captured)
    \\\" - another quote
    .*   - anything
    

    但是,不使用正则表达式要容易得多:

    "your \"string\" here".split("\"")[1]
    

    【讨论】:

    • 有没有不使用正则表达式的方法?
    • @cody string.split("\"")[1]
    • @cody String[] arr = string.split("\""); //first string is in arr[1] and second is in arr[3]
    • 但这只有在我们知道字符串以及它有多少引号时才有效。对于其中包含随机数量引号的随机文本,您有什么建议?我在寻找更像是报价查找器方法的东西...?
    • @cody String[] arr = string.split("\""); for (int i = 1; i < arr.length; i += 2) { /* use arr[i] */ }
    【解决方案2】:

    其实你会得到IllegalStateException

    public class RegexDemo {
        public static void main(String[] args) {
            Pattern p = Pattern.compile(".*\\\"(.*)\\\".*");
            Matcher m = p.matcher("your \"string\" here");
            System.out.println(m.group(1));
        }
    }
    

    它给出:

    Exception in thread "main" java.lang.IllegalStateException: No match found
        at java.util.regex.Matcher.group(Matcher.java:485)
        at RegexDemo.main(RegexDemo.java:11)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
    

    在使用group()之前,您需要调用find()matches()

    简单测试,例如:

    public class RegexTest {
        @Test(expected = IllegalStateException.class)
        public void testIllegalState() {
            String string = new String("your \"string\" here");
            Pattern pattern = Pattern.compile(".*\\\"(.*)\\\".*");
            Matcher matcher = pattern.matcher(string);
    
            System.out.println(matcher.group(1));
        }
    
        @Test
        public void testLegalState() {
            String string = new String("your \"string\" here");
            Pattern pattern = Pattern.compile(".*\\\"(.*)\\\".*");
            Matcher matcher = pattern.matcher(string);
    
            if(matcher.find()) {
                System.out.println(matcher.group(1));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 2017-06-18
      • 1970-01-01
      • 2018-01-25
      • 2023-02-23
      • 2019-08-04
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多