我正在處理一些字串并嘗試決議資料并檢索位于字串末尾第三次出現“ - ”之前的字串。該資料來自資料庫的字串,并且在決議時我想排除一些文本“-NONE----”。
輸入(下面的輸入是一個字串而不是串列)
String input1 = "-A123456-B987-013691-000-109264821"
String input2 = "-NONE----"
String input3 = "C1234567-A1241-EF-012361-000-18273460"
輸出
String output1 = "-A123456-B987"
String output2= "-NONE----"
String output3 = "C1234567-A1241-EF"
從字串的開頭開始,我需要在找到第三次出現
“ - ”(連字符)之前檢索資料,但我需要從字串末尾開始計算“ - ”(連字符)出現的次數。
任何提示表示贊賞。
uj5u.com熱心網友回復:
您可以使用正則運算式替換方法:
String input = "-A123456-B987-013691-000-109264821";
String output = "([^-]*(?:-[^-] ){2}).*", "$1");
System.out.println(output); // -A123456-B987
此處使用的正則運算式模式表示匹配:
(打開捕獲組[^-]*匹配可選的第一項(?:-[^-] ){2}然后匹配 - 和一個術語,兩次
)關閉捕獲組,可用作$1.*消耗字串的剩余部分
uj5u.com熱心網友回復:
您可以將后面的三個破折號與$符號匹配,然后提取其前面的所有內容。我創建了兩個捕獲組,其中第一個是您要提取的內容:
private static String extractFront(String input1) {
if(input1.equals("-NONE----")) {
return input1;
} else {
Pattern pattern = Pattern.compile("(.*)(-[^-]*){3}$");
Matcher matcher = pattern.matcher(input1);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
主要測驗:
public static void main(String[] args) {
String input1 = "-A123456-B987-013691-000-109264821";
String input2 = "-NONE----";
String input3 = "C1234567-A1241-EF-012361-000-18273460";
System.out.println(extractFront(input1));
System.out.println(extractFront(input2));
System.out.println(extractFront(input3));
}
輸出:
-A123456-B987
-NONE----
C1234567-A1241-EF
編輯:@stubbleweb1995 添加if了完整解決方案的條件
uj5u.com熱心網友回復:
我們可以使用流、lambda 和謂詞。
將您的輸入拆分為行尾字符,以獲取字串陣列。我們過濾掉“NONE”行。
對于每一行,我們使用連字符作為分隔符將其分成幾部分。這為我們提供了一個字串陣列,我們僅使用 3 個部分重新組合這些字串。
最后我們收集到一個串列中。
這是一些未經測驗的代碼,可以幫助您入門。
String[] lines = input.split( "\n" ) ;
List < String > results =
Arrays
.stream( lines )
.filter( line -> ! line.contains( "-NONE-" )
.map(
line -> {
String.join(
"-" ,
Arrays.copyOf( line.split( "-" , 4 ) , 3 , String[].class )
)
}
)
.toList()
;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/510518.html
標籤:爪哇细绳分隔符
