[英]Pattern matcher in Java
我想要這樣的模式匹配器的結果
finalResult = "1. <b>Apple</b> - Apple is a fruit 2. <b>Caw</b> - Caw is an animal 3. <b>Parrot</b> - Parrot is a bird";
我嘗試過這種方式:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird";
String finalResult = "";
Pattern pat = Pattern.compile("\\d\\.(.+?)-");
Matcher mat = pat.matcher(test);
int count = 0;
while(mat.find()){
finalResult += test.replaceAll(mat.group(count), "<b>" + mat.group(count) + "</b>");
count++;
}
您可以直接使用test.replaceAll()
而不是Pattern.matcher()
,因為replaceAll()
自己接受正則表達式。
和要使用的正則表達式就像"(?<=\\\\d\\\\. )(\\\\w*?)(?= - )"
。
所以你的代碼將是
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird";
String finalResult = "";
finalResult = test.replaceAll("(?<=\\d\\. )(\\w*?)(?= - )", "<b>" + "$1" + "</b>");
您可以使用Matcher
類的replaceAll
方法。 ( javadoc )
碼:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird";
String finalResult = "";
Pattern pat = Pattern.compile("(\\d+)\\.\\s(.+?)\\s-");
Matcher mat = pat.matcher(test);
if (mat.find()){
finalResult = mat.replaceAll("$1. <b>$2</b> -");
}
System.out.println(finalResult);
replace all
用指定的正則表達式replace all
字符串的所有匹配項。 $1
和$2
是捕獲的組(例如list的第一個元素的'1'和'Apple')。
我稍微修改了您的正則表達式:
(\\\\d+)
捕獲多位數字(不僅是0-9)。 同樣,它“保存”在組1中 \\\\s
符號,與空格符號匹配 @Codebender的解決方案更為緊湊,但是您始終可以使用String.split()
方法:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird";
String[]tokens = test.split("-\\s*|\\d\\.\\s*");
StringBuffer result = new StringBuffer();
int idx = 1;
while (idx < (tokens.length - 1))
{
result.append("<b>" + tokens[idx++].trim() + "</b> - " + tokens[idx++].trim() + ". ");
}
System.out.println(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.