![](/img/trans.png)
[英]regex to capture the string between a word and first occurrence of a character
[英]Regex to extract string between the first and last occurrence of a character
我目前正在從“違反異常錯誤”消息中提取特定的字符串。 我所做的步驟如下:
輸入字符串格式:密鑰鍵的重復輸入值
正則表達式當前正在使用:
Duplicate entry '(.*)' for key '(.*)'
獲得第1組: 價值
值的格式==> 一些ID- 所需值 - 一些ID
要提取所需的值,我目前使用(-)的第一個索引和最后一個索引,並按如下所示提取字符串:
error.substring(error.indexOf("-") + 1, error.lastIndexOf("-"));
只能通過正則表達式來完成嗎?
我們可以使用String#replaceAll
使用String#replaceAll
來做到這一點:
String input = "some id-desired - d - d- value-some id";
String output = input.replaceAll("^.*?-(.*)-.*", "$1");
System.out.println(output);
輸出:
desired - d - d- value
我謹慎使用的模式會消耗掉所有東西,直到第一個破折號為止。 然后,它貪婪地消耗了第一個破折號和最后一個破折號之間的所有內容。 樣本數據很奇怪,但我想證明答案對於所需數據中出現的破折號是可靠的。
或多或少直截了當
var pattern = Pattern.compile("-.*-");
var matcher = pattern.matcher(string);
if (matcher.find())
result = matcher.group();
->查找第一個出現的-
后跟盡可能多的字符,后跟一個-
。 如果期望值中存在-
這也適用。
缺點是,破折號包含在結果中,但可以使用substring()
輕松將其substring()
。 可以使用正向超前/后向避免:
...compile("(?<=-).*(?=-)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.