2014-01-26 75 views
0

我正在尋找帶有捕獲組的正則表達式,其中問號(?)可以出現在我的輸入字符串中。如果不存在,則返回輸入字符串,但如果存在?,則返回第一個出現?之前的字符串。使用正則表達式捕獲預期結果

我的輸入可以以以下格式

Pattern 1 
abc.txt // result should be abc.txt 
Pattern 2 
abc.txt?param1=qwerty.controller&param2=xsd.txt // result should be abc.txt 

我試過下面

Matcher matcher = Pattern.compile("(.*?)\\?").matcher(str1); 
String group1 = ""; 
if (matcher.find()) { 
    group1 = matcher.group(); 
} 

有了這個,我能夠捕捉到預期的結果爲模式2,但我不知道如何修改它所以我可以 捕獲模式1和模式2的預期結果。

更新: - 我知道如果group1是空字符串,我可以找出該輸入字符串不包含任何?輸入字符串是這裏的預期輸出。但我在尋找是否可以用單個正則表達式捕獲這兩種模式?

回答

1

你可以使用一個否定類像這樣:

^[^?]+ 

regex101 demo

^首先確保比賽始於開始。

[^?]+匹配所有非?個字符(如果沒有,則匹配到結束)。

1

一種方法是從你的字符串開始的第一個問號去掉了一切,就像這樣:

String res = orig.replaceAll("[?].*$", ""); 

如果沒有問號,表達將沒有匹配,那麼你會得到原始字符串。否則,表達式將匹配從問號開始的所有內容,因此replaceAll將刪除它,因爲替換字符串爲空。

String orig = "abc.txt?param1=qwerty.controller&param2=xs?d.txt"; 
String res = orig.replaceAll("[?].*$", ""); 
System.out.println(res); 
orig = "hello world"; 
res = orig.replaceAll("[?].*$", ""); 
System.out.println(res); 

這將打印

abc.txt 
hello world 

Link to a demo on ideone.

編輯:我想用一個正則表達式

您可以使用"^[^?]*"爲您的正則表達式來同時捕捉。 ^定位到開頭,而[^?]捕獲所有內容 - 直到字符串的末尾或第一個問號。無論哪種方式,問號都會被排除。

下面是代碼:

String[] strings = new String[] {"abc.txt?param1=qwerty.controller&param2=xs?d.txt", "Hello, world!", "a?b"}; 
for (String str1 : strings) { 
    Matcher matcher = Pattern.compile("^[^?]*").matcher(str1); 
    String group1 = ""; 
    if (matcher.find()) { 
     group1 = matcher.group(); 
    } 
    System.out.println(group1); 
} 

Second demo on ideone.

1

更換第一?和一切(如果存在)後:

str = str.replaceAll("\\?.*", ""); 
+0

dasblinkenlight也說同樣的東西,但你的正則表達式更簡單:) –