1 package org.jical; 2 3 import java.util.Map ; 7 import java.util.regex.Matcher ; 8 import java.util.regex.Pattern ; 9 10 public class ContentLineParser { 11 12 private static final String RR_ALPHA = "A-Za-z"; 13 private static final String RR_DIGIT = "0-9"; 14 private static final String RR_DQUOTE = "\\\""; 15 private static final String RR_WSP = " \\t"; 16 private static final String RR_CTL = "\\x00-\\x08\\x0A-\\x1F\\x7F"; 17 private static final String RR_SEP = ";:,"; 18 19 private static final String R_QSAFE_CHAR = "[^"+RR_CTL+RR_DQUOTE+"]"; 20 private static final String R_SAFE_CHAR = "[^"+RR_CTL+RR_DQUOTE+RR_SEP+"]"; 21 private static final String R_VALUE_CHAR = "[^"+RR_CTL+"]"; 22 private static final String R_NAME_CHAR = "[\\-"+RR_ALPHA+RR_DIGIT+"]"; 23 24 private static final String RC_PARAM_VALUE = "(?:(?:"+RR_DQUOTE+"("+R_QSAFE_CHAR+"*)"+RR_DQUOTE+")|("+R_SAFE_CHAR+"*))"; 25 private static final String RC_PARAM = "("+R_NAME_CHAR+"*)="+RC_PARAM_VALUE+"[;:]"; 26 private static final String RC_NAME = "("+R_NAME_CHAR+"*)[;:]"; 27 28 private static final Pattern NAME_PATTERN = Pattern.compile( RC_NAME ); 29 private static final Pattern PARAM_PATTERN = Pattern.compile( RC_PARAM ); 30 31 public static ContentLine parse( CharSequence cs ) { 32 Matcher nameMatcher = NAME_PATTERN.matcher( cs ); 33 Matcher paramMatcher = PARAM_PATTERN.matcher( cs ); 34 int start = 0; 35 if ( nameMatcher.find( start ) ) { 36 MutableContentLine contentLine = new MutableContentLine(); 37 { 38 contentLine.setRawLine( cs.toString() ); 39 } 40 { 41 contentLine.setName( nameMatcher.group( 1 ) ); 42 start = nameMatcher.end(); 43 } 44 if ( cs.charAt( start - 1 ) == ';' ) { 45 Map params = contentLine.getMutableParameters(); 46 while ( paramMatcher.find( start ) ) { 47 String key = paramMatcher.group(1); 48 String val = paramMatcher.group(2); 49 if ( val == null ) { 50 val = paramMatcher.group(3); 51 } 52 params.put( key, val ); 53 start = paramMatcher.end(); 54 } 55 } 56 { 57 contentLine.setValue( cs.subSequence( start, cs.length() ).toString() ); 58 } 59 return contentLine; 60 } 61 return null; 62 } 63 } 64 | Popular Tags |