2017-06-07 77 views
1

我想匹配的是啓動並用相同的報價結尾的字符串,但只有在開始引號和結束:使用lookahead來匹配以引號開頭和結尾並刪除引號的字符串?

"foo bar" 
'foo bar' 
"the quick brown fox" 

但我不希望這些匹配或剝離:

foo "bar" 
foo 'bar' 
'foo bar" 
"the lazy" dogs 

我試着用這個Java正則表達式,但它確實不是所有的情況下,相當的工作:

Pattern.compile("^\"|^'(.+)\"$|'$").matcher(quotedString).replaceAll(""); 

我認爲是有辦法做到超前,但我不知道怎麼牛逼o在這種情況下使用它。

或者設置一個分別檢查它們的if語句會更高效嗎?

Pattern startPattern = Pattern.compile("^\"|^'); 
Pattern endPattern = Pattern.compile(\"$|'$"); 

if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) { 
    ... 
} 

(當然,這將匹配'foo bar",我不想)

+0

你是說你想在圍繞兩個或更多單詞s時去除單引號或雙引號在引號內部用空格分開? –

+0

如果字符串在中間有引號會怎麼樣? (例如'這是我的棕色狐狸') –

+0

@MichaelMarkidis - 我並不擔心那個角落案件,這與命令行的東西有關,因此無論如何都是無效的。 – marathon

回答

3

你正在尋找的正則表達式是

^(["'])(.*)\1$ 

與替換字符串爲"$2"

Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$"); 
String output = pattern.matcher(input).replaceAll("$2"); 

演示:https://ideone.com/3a5PET

2

這裏有一個方法,可以檢查您的所有需求:

public static boolean matches (final String str) 
{ 
    boolean matches = false; 

    // check for null string 
    if (str == null) return false; 

    if ((str.startsWith("\"") && str.endsWith("\"")) || 
     (str.startsWith("\'") && str.endsWith("\'"))) 
    { 
     String strip = str.substring(1, str.length() - 1); 

     // make sure the stripped string does not have a quote 
     if (strip.indexOf("\"") == -1 && strip.indexOf("\'") == -1) 
     { 
      matches = true; 
     } 
    } 
    return matches; 
} 

測試

public static void main(String[] args) 
{ 
    System.out.println("Should Pass\n-----------"); 
    System.out.println(matches("\"foo bar\"")); 
    System.out.println(matches("\'foo bar\'")); 
    System.out.println(matches("\"the quick brown fox\"")); 

    System.out.println("\nShould Fail\n-----------"); 
    System.out.println(matches("foo \"bar\"")); 
    System.out.println(matches("foo \'bar\'")); 
    System.out.println(matches("'foo bar\"")); 
    System.out.println(matches("\"the lazy\" dogs")); 

} 

輸出

Should Pass 
----------- 
true 
true 
true 

Should Fail 
----------- 
false 
false 
false 
false 
相關問題