001package org.unix4j.unix.grep;
002
003import java.util.regex.Pattern;
004
005import org.unix4j.line.Line;
006
007/**
008 * A matcher using regular expressions to match the pattern with a line. Uses
009 * Java's {@link Pattern} to do the regexp stuff.
010 */
011class RegexpMatcher implements LineMatcher {
012
013        private final Pattern pattern;
014
015        public RegexpMatcher(GrepArguments args) {
016                if(args.isPatternSet()){
017                        this.pattern = args.getPattern();
018                } else if(args.isRegexpSet()){
019                        final String regex;
020                        if (args.isWholeLine()) {
021                                regex = args.getRegexp();
022                        } else {
023                                regex = ".*" + args.getRegexp() + ".*";
024                        }
025                        this.pattern = Pattern.compile(regex, args.isIgnoreCase() ? Pattern.CASE_INSENSITIVE : 0);
026                } else {
027                        throw new IllegalArgumentException("Either pattern, or patternStr must be given");
028                }
029        }
030
031        @Override
032        public boolean matches(Line line) {
033                // NOTE: we use content here because . does not match line
034                // ending characters, see {@link Pattern#DOTALL}
035                boolean matches = pattern.matcher(line.getContent()).matches();
036                return matches;
037        }
038}