简体   繁体   中英

java regex split strings

Regex to fetch strings enclosed inside "${VALUE}" using java regular expression throws exception

public static void main(String[] args) {

        String test = "Report for ${PROCESS_NAME} with status ${PROCESS_STATUS}";
        String[] results = test.split("\\${([^\\{\\}]*)\\}");
        for (String result : results) {
            System.err.println(result);
        }
    }



Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1
\${([^\{\}]*)\}
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.closure(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)

Expected array: results = PROCESS_NAME, PROCESS_STATUS;

Input test string is not fixed length. Whats wrong in the regex.

I suggest this solution

    Matcher m = Pattern.compile("\\$\\{(.+?)\\}").matcher(test);
    while(m.find()) {
        System.out.println(m.group(1));
    }

You need to escape { as well:

test.split("\\$\\{([^\\{\\}]*)\\}")

Also you don't have to escape {} inside character class:

test.split("\\$\\{([^{}]*)\\}")

You probably lost one '\\' in your regexp. It should look like that: "\\\\$\\\\{([^\\\\{\\\\}]*)\\\\}" .

However, split() method will not do what you want. As marked here

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

You need to find substrings matching specified pattern. That could be done like that:

String patternString = "\\$\\{([^\\{\\}]*)\\}";
List<String> results = new ArrayList<String>();

String test = "Report for ${PROCESS_NAME} with status ${PROCESS_STATUS}";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher();

while(matcher.find()) {
     results.add(matcher.group(1));
}

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