The Java String class has a matches(String regex) method that checks whether the current string matches the given regular expression. However, how can we find whether a substring of the current string would match the regular expression?
I am trying to mimic the behavior of grep using Java. grep takes a line and prints all those lines that match the given regular expression anywhere in the line. I am not sure how to do that with Java, because the matches method checks whether the entire line (ie string) matches the regex and not any substring within it.
Matcher#find()
方法Matcher#find()
您的需求
就像ColinD所说的那样,最好的选择是一次在字符串中读一行,然后在两端都使用一个不愿意的通配符来运行正则表达式。
You can modify the regular expression to allow wildcards at the front and back of the string.
So instead of:
Pattern regex = Pattern.compile("hello\\sworld")
you have
Pattern regex = Pattern.compile(".*hello\\sworld.*);
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.