[英]How to match whole word in regex using java split
我正在嘗試根據我的要求拆分單詞。 我想根據整個單詞進行拆分。
如下所示的示例,
Actual - Expecting
10% to 20% - 10 to 20%
10% and 60% - 10 and 60%
5 % to 10 % - 5 to 10%
25 to 125 - no need to change
我的示例字符串
String str = "Zimowski, M. F., Muraki, E., Mislevy, R 10% to 25% J., & Btock, R. D. (1996). BILOG-MG: [mMultiple 10% and 25%-group IRT]( analysis and test maintenance for binary items. Chicago, IL: 5% Scientific) Software).[AQ: “Zimowski,10 % to 25% Muraki, Mislevy, & Bock, 1996�is not cited 10 to 25% in text. Please indicate where a citation 10 and 25% should appear or allow us to delete the reference.]";
我的預期結果
String result = "Zimowski, M. F., Muraki, E., Mislevy, R 10 to 25% J., & Btock, R. D. (1996). BILOG-MG: [mMultiple 10 and 25%-group IRT]( analysis and test maintenance for binary items. Chicago, IL: 5% Scientific) Software).[AQ: “Zimowski,10 to 25% Muraki, Mislevy, & Bock, 1996�is not cited 10 to 25% in text. Please indicate where a citation 10 and 25% should appear or allow us to delete the reference.]";
我嘗試在出現“ and”,“ to”時拆分字符串。 但顯然還沒有完成(根據要求)。
因此,請提出建議並讓我知道。
嘗試這個:
str = str.replaceAll("(\\\\d\\\\d?\\\\d?\\\\s?)(%)(\\\\s)(and|to)(\\\\s\\\\d\\\\d?\\\\d?\\\\s?)","$1$3$4$5");
看一下java.util.regex.Matcher類,特別是方法appendReplacement。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SanJose {
public static void main(String[] args) {
String myString = "10% to 20% aaa 10% and 60% bbb 5 % to 10 % ddd 25 to 125";
Pattern p = Pattern.compile("\\d+\\s*%\\s+(to|and)");
Matcher m = p.matcher(myString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().replace("%", ""));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.