我正在开发一个Java程序来替换文本文件中的变量值。
要替换的变量封装为......
side /*{{*/ red /*TEAM}}*/
或
detect_range /*{{*/ 200 /*RANGE}}*/ nm
所以在第一种情况下,我想用另一个值替换红色值。第二个我会替换200。
在这里,我逐行阅读文件,寻找该模式。
File file = new File(currentFile);
try {
Scanner scanner = new Scanner(file);
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (<match regex expression for xxxxx /*{{*/ value /*VariableNAME}}*/ >) {
}
}
} catch (Exception e) {
System.out.println(e.toString());
//handle this
}
什么是正则表达式,我可以用它来找到这些模式?
编辑:
我在文件中有一行说
side /*{{*/ red /*TEAM}}*/
输出将文件中的行更改为
side /*{{*/ blue /*TEAM}}*/
字符串“TEAM”是标识符。
答案 0 :(得分:1)
您可以使用以下String.replaceAll()
方法使用。
(?<=\/\*\{\{\*\/ ).*?(?= \/\*(TEAM|RANGE)\}\}\*\/)
注意:如果值为&#34; TEAM&#34;则使用\w+
和&#34; RANGE&#34;是动态的。
示例代码:
String str1 = "side /*{{*/ red /*team}}*/ ";
String str2 = "detect_range /*{{*/ 200 /*RANGE}}*/ nm";
String pattern = "(?i)(?<=\\/\\*\\{\\{\\*\\/ ).*?(?= \\/\\*(TEAM|RANGE)\\}\\}\\*\\/)";
System.out.println(str1.replaceAll(pattern, "XXX"));
System.out.println(str2.replaceAll(pattern, "000"));
输出:
side /*{{*/ XXX /*team}}*/
detect_range /*{{*/ 000 /*RANGE}}*/ nm
如果你想得到&#34; TEAM&#34;或&#34; RANGE&#34;然后从索引1获取它。
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str1);
if (m.find()) {
System.out.println(m.group(1));
}
答案 1 :(得分:0)