[英]Java - Regular Expressions Split on character after and before certain words
我在弄清楚如何使用JAVA中的正則表達式抓取字符串的特定部分時遇到了麻煩。 這是我的輸入字符串:
application.APPLICATION NAME.123456789.status
我需要獲取名為"APPLICATION NAME"
的字符串部分。 由於APPLICATION NAME
本身可能包含一個句點,因此我不能簡單地對句點字符進行拆分。 第一個單詞"application
”將始終保持不變, "APPLICATION NAME"
之后的字符將始終是數字。
我已經可以按時間段分割並獲取第一個索引,但是正如我提到的, APPLICATION NAME
本身可能包含時間段,所以這不好。 我也已經能夠獲取一個時期的第一個和倒數第二個索引,但這似乎效率不高,並且希望通過使用REGEX來面向未來。
我已經在Google搜尋了幾個小時,卻找不到太多指導。 謝謝!
您可以將^application\\.(.*)\\.\\d
與find()
,或者將application\\.(.*)\\.\\d.*
與matches()
。
使用find()
示例代碼:
private static void test(String input) {
String regex = "^application\\.(.*)\\.\\d";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find())
System.out.println(input + ": Found \"" + m.group(1) + "\"");
else
System.out.println(input + ": **NOT FOUND**");
}
public static void main(String[] args) {
test("application.APPLICATION NAME.123456789.status");
test("application.Other.App.Name.123456789.status");
test("application.App 55 name.123456789.status");
test("application.App.55.name.123456789.status");
test("bad input");
}
輸出量
application.APPLICATION NAME.123456789.status: Found "APPLICATION NAME"
application.Other.App.Name.123456789.status: Found "Other.App.Name"
application.App 55 name.123456789.status: Found "App 55 name"
application.App.55.name.123456789.status: Found "App.55.name"
bad input: **NOT FOUND**
只要“狀態”不是以數字開頭,上述內容就可以使用。
使用split()
,可以將key.split("\\\\.")
保存在String[] s
然后第二次從s[1]
到s[s.length-3]
。
使用正則表達式,您可以執行以下操作:
String appName = key.replaceAll("application\\.(.*)\\.\\d+\\.\\w+")", "$1");
為什么要分裂? 只是:
String appName = input.replaceAll(".*?\\.(.*)\\.\\d+\\..*", "$1");
這也可以正確處理應用程序名稱中的點號和數字,但只有在您知道輸入格式為預期格式時,才能正確運行。
要在模式不匹配時通過返回空白來處理“錯誤”輸入,請更加嚴格,並使用始終匹配(替換)整個輸入的可選選項:
String appName = input.replaceAll("^application\\.(.*)\\.\\d+\\.\\w+$|.*", "$1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.