javaregexflex-lexerjflex

JFLEX regular expressions for string starts with


I'm new with this jflex and regular expressions I read a lot even though I know I faced the solution in the manual but really I can't understand these regular expressions. I want simple read a text file with jflex and return every line that starts with name = or name= but this was a pain for me for 1 week I'm reading all regular expressions in the jflex document but I can't understand which one I can use to achieve it anyone can help me out? with jflex rules and any code to contain that?

this is the example input and output

bla bla bla
bla bla bla
name=StackOverFlow
name = ThisIsGo
bla bla bla

Output:

StackOverFLow

ThisIsGo


Solution

  • If you need to match something placed after the equal sign preceded by the word name, then you could simply describe that syntax and use a capturing group to enclose the value after the equal sign.

    name\s*=\s*(.+)
    

    Test Link

    Here you can test the regex above:

    https://regex101.com/r/FMXSDK/1

    Code Snippet

    Your code would look like this:

    String str = "bla bla bla\n" +
            "bla bla bla\n" +
            "name=StackOverFlow\n" +
            "name = ThisIsGo\n" +
            "bla bla bla";
    
    Pattern pattern = Pattern.compile("name\\s*=\\s*(.+)");
    Matcher matcher = pattern.matcher(str);
    
    while (matcher.find()){
        System.out.println(matcher.group(1));
    }
    

    Output

    StackOverFlow
    ThisIsGo