简体   繁体   中英

Regex expression to find

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.

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));
}

You can use this regex:

/\*{{\*/ *(\S+) */\*[^}]*}}\*/

and grab captured group #1

RegEx Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM