SleelaRegexNatural.java
regex/java/SleelaRegexNatural.java · 6 line(s) · java
package sleela.regex;
import java.util.Map;
import static java.util.Map.entry;
/** Finite Natural Form vocabulary and structural validator. */
public final class SleelaRegexNatural { private SleelaRegexNatural(){} private static final Map<String,String> SYMBOLS=Map.ofEntries(entry("any","."),entry("digit","[0-9]"),entry("letter","[A-Za-z]"),entry("space","\\s"),entry("one","="),entry("optional","?"),entry("some","+"),entry("many","*"),entry("begin","^"),entry("end","$"),entry("or","|")); public static String canonicalSymbol(String word){return SYMBOLS.getOrDefault(word,"");} public static void validate(String source){if(source==null||source.isEmpty())throw new IllegalArgumentException("empty Natural Form pattern");int depth=0;boolean quote=false;for(int i=0;i<source.length();){char c=source.charAt(i);if(c=='"'){quote=!quote;i++;continue;}if(quote){i++;continue;}if(c=='('||c=='['||c=='<')depth++;else if(c==')'||c==']'||c=='>'){if(depth==0)throw new IllegalArgumentException("unbalanced closing delimiter at "+i);depth--;}if(Character.isLetter(c)){int j=i+1;while(j<source.length()&&Character.isLetter(source.charAt(j)))j++;String w=source.substring(i,j);if(!SYMBOLS.containsKey(w))throw new IllegalArgumentException("unknown Natural Form word: "+w);i=j;continue;}i++;}if(quote||depth!=0)throw new IllegalArgumentException("unbalanced Natural Form pattern");}}