Grepping for string package info.compute.example; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Grep { public static void main(String[] args) { String str = "line1\nline2\nline3"; System.out.println(str); System.out.println("grepTest for line2 returns: " + grepTest(str, "line2")); System.out.println("grepLine for line2 returns: " + grepLine(str, "line2")); } private static boolean grepTest(String str, String patt) { Pattern pat = Pattern.compile(patt); Matcher mat; mat = pat.matcher(str); if(mat.find()) return true; return false; } private static String grepLine(String str, String patt) { Pattern pat = Pattern.compile(patt); Matcher mat; String[] lines = str.split("\\n"); for(String s: lines) { mat = pat.matcher(s); if(mat.find()) return s; } return ""; } } |
Java >