[英]extract specific word from comma separated string in java using regex
輸入 - [1, 1111, 2020, BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558]
我想在這里提取 BMW 並且我正在使用(^(?:[^\\,]*\\,){3})
這個正則表達式。 這導致 - BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558]
。 任何人都可以幫我解決這個問題嗎? 提前致謝
如果它是逗號分隔的字符串,您可以將 function 從字符串 class 中拆分出來,這會將逗號分隔的字符串轉換為數組。 參考 -鏈接
string split() 方法在給定正則表達式的匹配項周圍打破給定字符串。
語法 - Public String [ ] split ( String regex, int limit )
Input String: 016-78967
Regular Expression: -
Output : {"016", "78967"}
然后你可以進入數組從中找出特定的關鍵字。
由於您只能在不使用組的情況下輸入模式,因此您可以在正向后視中使用有限重復,例如{0,1000}
,因為 Java 不支持無限重復。
(?<=^\\[[^,]{0,1000},[^,]{0,1000},[^,]{0,1000},\\h{0,10})\\w{3,10}(?=[^\\]\\[]*\\])
解釋
(?<=
Positive lookbehind, assert what is on the left is
^\[
字符串開始,匹配[
[^,]{0,1000},[^,]{0,1000},[^,]{0,1000},
匹配除,
后跟,
之外的任何字符 3 次\h{0,10}
匹配 0-10 次水平空白字符)
近距離觀察\w{3,10}
匹配 3-10 個單詞字符(?=
正向前瞻,斷言右邊是
[^\]\[]*\]
匹配直到]
)
關閉前瞻代碼示例
final String regex = "(?<=^\\[[^,]{0,1000},[^,]{0,1000},[^,]{0,1000},\\h{0,10})\\w{3,10}(?=[^\\]\\[]*\\])";
final String string = "[1, 1111, 2020, BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558]";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
Output
BMW
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.