簡體   English   中英

在Java中使用正則表達式在雙引號之間提取子字符串

[英]Extract a substring between double quotes with regular expression in Java

我有一個像這樣的字符串:

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

我想在Java中使用regexp提取“adc,def”(不帶引號),我該怎么辦?

如果你真的想使用正則表達式:

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]

實際上你會得到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));
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM