Reputation: 354
I am working on a Java program that replaces variable values in a text file.
The variables to be replaced are encapsulated as...
side /*{{*/ red /*TEAM}}*/
or
detect_range /*{{*/ 200 /*RANGE}}*/ nm
So in the first case I want to replace the value red with another value. The second I would replace 200.
Here I am reading the file line by line looking for that pattern.
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
}
What is a regex expression to that I Could use to find these patterns?
Edit:
I have a line in the file that would say
side /*{{*/ red /*TEAM}}*/
The output change the line in the file to
side /*{{*/ blue /*TEAM}}*/
The string "TEAM" is the identifier.
Upvotes: 0
Views: 47
Reputation: 46841
You can use below use with String.replaceAll()
method.
(?<=\/\*\{\{\*\/ ).*?(?= \/\*(TEAM|RANGE)\}\}\*\/)
Here is online demo
Note: Use \w+
if value "TEAM" and "RANGE" are dynamic.
Sample code:
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"));
output:
side /*{{*/ XXX /*team}}*/
detect_range /*{{*/ 000 /*RANGE}}*/ nm
If you want to get "TEAM" or "RANGE" then get it from index 1.
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str1);
if (m.find()) {
System.out.println(m.group(1));
}
Upvotes: 1
Reputation: 785246
You can use this regex:
/\*{{\*/ *(\S+) */\*[^}]*}}\*/
and grab captured group #1
Upvotes: 0