REGEX:查找模式,提取数据,并用与搜索内容相关的字符串替换搜索的模式
正如标题所说,我想: 1) 找到一个模式。示例:从该字符串中获取$(getThisString+100):“这是一个随机字符串$(getThisString+100)” 2) 提取数据。例如:从$中获取值100(getThisString+100) 3) 将搜索的模式替换为与搜索内容相关的字符串。例如:用150(100+50)替换$(getThisString+100)(这50是我刚才编的任何数字) 最后,我需要“这是一些随机字符串150” 我对regex很陌生,如果可能的话请告诉我 非常感谢这个怎么样REGEX:查找模式,提取数据,并用与搜索内容相关的字符串替换搜索的模式,regex,string,replace,Regex,String,Replace,正如标题所说,我想: 1) 找到一个模式。示例:从该字符串中获取$(getThisString+100):“这是一个随机字符串$(getThisString+100)” 2) 提取数据。例如:从$中获取值100(getThisString+100) 3) 将搜索的模式替换为与搜索内容相关的字符串。例如:用150(100+50)替换$(getThisString+100)(这50是我刚才编的任何数字) 最后,我需要“这是一些随机字符串150” 我对regex很陌生,如果可能的话请告诉我 非常感谢这
package myparser;
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class ParseTest {
private final Pattern re = Pattern.compile(".*?(\\$\\(getThisString\\+(\\d+)\\)).*");
public String parseMyString(final String str) {
Matcher m = re.matcher(str);
if (m.matches()) {
int val = Integer.parseInt(m.group(2));
int newVal = val + 50;
String strStart = str.substring(0, m.start(1));
String strEnd = str.substring(m.end(1));
return parseMyString(strStart + String.valueOf(newVal) + strEnd);
} else {
return str;
}
}
@Test
public void testParseNone() {
String in = "this is some random string)";
String out = parseMyString(in);
assertEquals(in, out);
}
@Test
public void testParseOne() {
String in = "this is some random string $(getThisString+100)";
String out = parseMyString(in);
assertEquals("this is some random string 150", out);
}
@Test
public void testParseMultiple() {
String in = "this is some random string $(getThisString+100) and some more random $(getThisString+60)";
String out = parseMyString(in);
assertEquals("this is some random string 150 and some more random 110", out);
}
}
注意事项:
- 以防你不知道:这是一个测试
- 我使用递归来解析多个字符串。在我看来,这更容易阅读。当您处理数千个替换时,这可能会导致堆栈溢出。在这种情况下,必须将递归重写为循环
s/100/150/
have fun根据你的回答,我认为正则表达式无法实现这一点。谢谢。当然awk
可以做这项工作,但是我不知道怎么做。。。