How to use java regex to match a line

后端 未结 2 1855
臣服心动
臣服心动 2020-11-27 20:10

The raw data is:

auser1 home1b
auser2 home2b
auser3 home3b

I want to match a line, but it doesn\'t work using ^(.*?)$

相关标签:
2条回答
  • 2020-11-27 20:32

    By default, ^ and $ match the start- and end-of-input respectively. You'll need to enable MULTI-LINE mode with (?m), which causes ^ and $ to match the start- and end-of-line:

    (?m)^.*$
    

    The demo:

    import java.util.regex.*;
    
    public class Main {
        public static void main(String[] args) throws Exception {
    
            String text = "auser1 home1b\n" +
                    "auser2 home2b\n" +
                    "auser3 home3b";
    
            Matcher m = Pattern.compile("(?m)^.*$").matcher(text);
    
            while (m.find()) {
                System.out.println("line = " + m.group());
            }
        }
    }
    

    produces the following output:

    line = auser1 home1b
    line = auser2 home2b
    line = auser3 home3b

    EDIT I

    The fact that ^.*$ didn't match anything is because the . by default doesn't match \r and \n. If you enable DOT-ALL with (?s), causing the . to match those as well, you'll see the entire input string being matched:

    (?s)^.*$
    

    EDIT II

    In this case, you mind as well drop the ^ and $ and simply look for the pattern .*. Since . will not match \n, you'll end up with the same matches when looking for (?m)^.*$, as @Kobi rightfully mentioned in the comments.

    0 讨论(0)
  • 2020-11-27 20:32

    we can also use the flag MULTILINE,

     Matcher m = Pattern.compile("^.*$",Pattern.MULTILINE).matcher(text);
    

    This will enable the multiline mode which will gave you the expected result.

    0 讨论(0)
提交回复
热议问题