您可以使用Pattern
和Matcher
像這樣:
public static void main(String[] args) throws Exception {
final String[] values = {"DBValue0", "DBValue1", "DBValue2", "DBValue3", "DBValue4", "DBValue5", "DBValue6", "DBValue7", "DBValue8", "DBValue9", "DBValue10"};
final String originaltext = "This is 4, This is 2, This is 7";
final Pattern pattern = Pattern.compile("(?<=This is)\\d++");
final Matcher matcher = pattern.matcher(originaltext);
final StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println(matcher.group());
final int index = Integer.parseInt(matcher.group());
matcher.appendReplacement(sb, values[index]);
}
matcher.appendTail(sb);
System.out.println(sb);
}
輸出:
4
2
7
This is DBValue4, This is DBValue2, This is DBValue7
編輯
繼OP的評論是似乎OP需求代替String
s的形式爲{name, index}
其中「name」是數組的名稱,「index」是該數組中元素的索引。
這很容易通過Map
平的陣列來實現的,以使用Map<String, String[]>
,然後使用Pattern
捕獲第一name
則index
他們的名字。
public static void main(String[] args) throws Exception {
final String[] companies = {"Company1", "Company2", "Company3"};
final String[] names = {"Alice", "Bob", "Eve"};
final String originaltext = "This is {company, 0}, This is {name, 1}, This is {name, 2}";
final Map<String, String[]> values = new HashMap<>();
values.put("company", companies);
values.put("name", names);
final Pattern pattern = Pattern.compile("\\{([^,]++),\\s*+(\\d++)}");
final Matcher matcher = pattern.matcher(originaltext);
final StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
final int index = Integer.parseInt(matcher.group(2));
matcher.appendReplacement(sb, values.get(matcher.group(1))[index]);
}
matcher.appendTail(sb);
System.out.println(sb);
}
輸出:
company
0
name
1
name
2
This is Company1, This is Bob, This is Eve
使用'Pattern'和'Matcher' –
你可以看看這篇文章:http://stackoverflow.com/questions/375420/java-equivalent- to-phps-preg-replace-callback –