正如标题所说,我想:
1)找到一个模式。例如:从这个字符串中获取$(getThisString + 100):“这是一些随机字符串$(getThisString + 100)”
2)提取数据。例如:从$(getThisString + 100)中获取值100
3)将搜索到的模式替换为与搜索内容相关的字符串。例如:将$(getThisString + 100)替换为150(100 + 50)(这50是我刚刚编写的任何数字)
所以最后,我需要“这是一些随机的字符串150”
我对正则表达式很陌生,如果可能,请告诉我。
非常感谢
答案 0 :(得分:0)
这个怎么样?
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);
}
}
备注:强>