[英]replace substring using regex
I have a string which contains many <xxx>
values. 我有一个包含许多
<xxx>
值的字符串。
I want to retrive the value inside <>
, do some manipulation and re-insert the new value into the string. 我想检索
<>
的值,进行一些操作,然后将新值重新插入字符串中。
What I did is 我所做的是
input = This is <abc_d> a sample <ea1_j> input <lmk_02> string
while(input.matches(".*<.+[\S][^<]>.*"))
{
value = input.substring(input.indexOf("<") + 1, input.indexOf(">"));
//calculate manipulatedValue from value
input = input.replaceFirst("<.+>", manipulatedValue);
}
but after the first iteration, value contains abc_d> a sample <ea1_j> input <lmk_02
. 但是在第一次迭代之后,值包含
abc_d> a sample <ea1_j> input <lmk_02
。 I believe indexOf(">") will give the first index of ">". 我相信indexOf(“>”)将给出“>”的第一个索引。 Where did I go wrong?
我哪里做错了?
This is a slightly easier way of accomplishing what you are trying to do: 这是完成您要尝试执行的操作的一种更简单的方法:
String input = "This is <abc_d> a sample <ea1_j> input <lmk_02> string";
Matcher matcher = Pattern.compile("<([^>]*)>").matcher(input);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, manipulateValue(matcher.group(1)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());
This is a good use case for the appendReplacement
and appendTail
idiom: 这是
appendReplacement
和appendTail
习惯用法的好用例:
Pattern p = Pattern.compile("<([^>]+)>");
Matcher m = p.matcher(input);
StringBuffer out = new StringBuffer():
while(m.find()) {
String value = m.group(1);
// calculate manipulatedValue
m.appendReplacement(out, Matcher.quoteReplacement(manipulatedValue));
}
m.appendTail(out);
尝试对正则表达式使用转义字符\\\\
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.