我在探索正則表達式。java正則表達式模式字符串格式
問題陳述:#和#之間的替換字符串與替換提供的值映射。
import java.util.regex.*;
import java.util.*;
public class RegExTest {
public static void main(String args[]){
HashMap<String,String> replacements = new HashMap<String,String>();
replacements.put("OldString1","NewString1");
replacements.put("OldString2","NewString2");
replacements.put("OldString3","NewString3");
String source = "#OldString1##OldString2#_ABCDEF_#OldString3#";
Pattern pattern = Pattern.compile("\\#(.+?)\\#");
//Pattern pattern = Pattern.compile("\\#\\#");
Matcher matcher = pattern.matcher(source);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, "");
buffer.append(replacements.get(matcher.group(1)));
}
matcher.appendTail(buffer);
System.out.println("OLD_String:"+source);
System.out.println("NEW_String:"+buffer.toString());
}
}
輸出:(套餐供應我的要求,但不知道是誰組(1)命令作品)
OLD_String:#OldString1##OldString2#_ABCDEF_#OldString3#
NEW_String:NewString1NewString2_ABCDEF_NewString3
如果我更改代碼,如下
Pattern pattern = Pattern.compile("\\#(.+?)\\#");
與
Pattern pattern = Pattern.compile("\\#\\#");
我得到以下錯誤:
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1
我不明白
"\\#(.+?)\\#" and `"\\#\\#"`
之間的區別,你能解釋的區別?
http://www.rexegg.com/regex-quickstart.html可能有幫助 – emotionlessbananas