Mega Code Archive

 
Categories / Java / Regular Expressions
 

Implement a pattern matcher for regular expressions

import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.text.DefaultFormatter; public class Main extends DefaultFormatter {   protected Matcher matcher;   public Main(Pattern regex) {     setOverwriteMode(false);     matcher = regex.matcher("");    }   public Object stringToValue(String string) throws java.text.ParseException {     if (string == null) return null;     matcher.reset(string);      if (! matcher.matches())        throw new java.text.ParseException("does not match regex", 0);     return super.stringToValue(string);   }   public static void main(String argv[]) {     Pattern evenLength = Pattern.compile("(..)*");     JFormattedTextField ftf1 = new JFormattedTextField(new Main(evenLength));     JLabel lab2 = new JLabel("no vowels:");     Pattern noVowels = Pattern.compile("[^aeiou]*",Pattern.CASE_INSENSITIVE);     Main noVowelFormatter = new Main(noVowels);     noVowelFormatter.setAllowsInvalid(false);      JFormattedTextField ftf2 = new JFormattedTextField(noVowelFormatter);   } }