In: Computer Science
RegEx (Regular Expressions)
Make 8 regular expressions to filter a specific data set in Java and explain what they do.
1.The . (dot) represents a single character example
System.out.println(Pattern.matches(".s", "as")); //returnstrue
because 2nd char is 's'
System.out.println(Pattern.matches(".s", "amms")); //returns false
because it has more than 2 char
System.out.println(Pattern.matches("..s", "mas")); //returns true
because 3rd char is 's'
2.Regular Expression Character classes Example
System.out.println(Pattern.matches("[amn]", "abcd")); //returns
false because (not a or m or n)
System.out.println(Pattern.matches("[amn]", "a")); //returns true
because (among a or m or n)
Regular Expression Character classes and Quantifiers Example
3. ? quantifier
System.out.println(Pattern.matches("[amn]?", "a")); //returns true
as (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa")); //returns
false as (a comes more than one time)
4. + quantifier
System.out.println(Pattern.matches("[amn]+", "aammmnn")); //returns
true as (a or m or n comes more than once)
System.out.println(Pattern.matches("[amn]+", "aazzta")); //returns
false as (z and t are not matching pattern)
5. * quantifier
System.out.println(Pattern.matches("[amn]*", "ammmna"));//returns
true (a or m or n may come zero or more times)
6. Regular Expression Metacharacters
Example
System.out.println(Pattern.matches("\\d", "abc"));//return false as
(non-digit)
System.out.println(Pattern.matches("\\d", "1"));//returns true as
(digit and comes once)
System.out.println(Pattern.matches("\\d", "4443"));//returns false
as (digit but comes more than once)
7. System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//returns true
8. // Following line prints "true" because the
whole
// text "hacksforhacks" matches pattern "hacksforha*ks"
System.out.println (Pattern.matches("hacksforha*ks",
"hacksforhacks"));
Sample program -
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static String REGEX = "dog"; private static String INPUT = "The dog says meow. " + "All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } }
Output
The cat says meow. All cats say meow.