我正在尋找帶有捕獲組的正則表達式,其中問號(?)可以出現在我的輸入字符串中。如果不存在,則返回輸入字符串,但如果存在?
,則返回第一個出現?
之前的字符串。使用正則表達式捕獲預期結果
我的輸入可以以以下格式
Pattern 1
abc.txt // result should be abc.txt
Pattern 2
abc.txt?param1=qwerty.controller¶m2=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是空字符串,我可以找出該輸入字符串不包含任何?輸入字符串是這裏的預期輸出。但我在尋找是否可以用單個正則表達式捕獲這兩種模式?
dasblinkenlight也說同樣的東西,但你的正則表達式更簡單:) –