Orby Orby - 11 months ago 32
Java Question

Regex Pattern to Split Word in A string Using An Identifier

I would like to split the following string by commas using a DOTALL regex pattern what will accept letters, numbers, whitespaces and special characters such as underscores and asterisks i.e.

@input("Test_1, Test_TWO , TEST_THIRTY_3*")
so the output would look like:

"Test_1",
"Test_TWO",
"TEST_THIRTY_3*"





public static void main(String args[])
{
String line = "@input(\"Test_1,Test_TWO , TEST_THIRTY_3*\"\\)\";
String pattern = "@input(\"(.*?)\".*";
Pattern r = Pattern.compile(pattern, Pattern.DOTALL);
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println("Found word: " + m.group(1) );
}

Answer Source

You have to escape the ( by \( so your regex should look like this @input\(\"(.*?)\".*, second you can use \s*,\s* to split the result like this :

String line = "@input(\"Test_1,Test_TWO , TEST_THIRTY_3*\"\\)";
String pattern = "@input\\(\"(.*?)\".*";
Pattern r = Pattern.compile(pattern, Pattern.DOTALL);
Matcher m = r.matcher(line);
while (m.find()) {
    System.out.println(Arrays.toString(m.group(1).split("\\s*,\\s*")));
    //----------------------------------------------------^^^^^^^^
}

outputs

[Test_1, Test_TWO, TEST_THIRTY_3*]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download