Home > Enterprise >  Regex to check the string pattern
Regex to check the string pattern

Time:11-23

From the following string have to check the presence of pattern [TEST-SELOGER][0][WARN][Tune][5121]

2021 Nov 22 07:07:03.373538 Process[15186]: [TEST-SELOGER][0][WARN][Tune][5121]GROUND TEST[0] test_tune: try: 1 format:

Here [TEST-SELOGER]- will not change

[0]- integer values only , negative values not supported

[WARN]-Value will not change

[Tune]- Value will not change

[5121]-Dynamic integer values, negative values not supported

Which regex I can use to check the presence of pattern [TEST-SELOGER][0][WARN][Tune][5121]

CodePudding user response:

You can use the below regex:

\[TEST-SELOGER\]\[([0-9] )\]\[WARN\]\[Tune\]\[([0-9] )\]

But, note that in Java, you need to use \\ instead of \.

Code:

import java.util.regex.*;

public class Main
{
    public static void main(String[] args) {
        String test = "2021 Nov 22 07:07:03.373538 Process[15186]: [TEST-SELOGER][0][WARN][Tune][5121]GROUND TEST[0] test_tune: try: 1 format:";
        Pattern pattern = Pattern.compile("\\[TEST-SELOGER\\]\\[([0-9] )\\]\\[WARN\\]\\[Tune\\]\\[([0-9] )\\]");
        Matcher matcher = pattern.matcher(test); 
        if (matcher.find())
        {
            System.out.println(matcher.group(1)   " "   matcher.group(2));
        }
        else
        {
            System.out.println("No match");
        }
        
    }
}
  • Related