Created
December 28, 2011 03:31
-
-
Save shawnlauzon/1526054 to your computer and use it in GitHub Desktop.
I wrote this to convert a string to a regular expression, since it was very similar. However I removed it because the algorithm they used was messed up.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given the badgeLayout that is almost-regex, convert it to something that | |
* is actually regex. | |
*/ | |
private void storeBadgeLayoutAsRegex(Context context, String str) { | |
// Given this: | |
// \02\02\02\0D\0A\03\1F\0D\0A{FIRSTNAME}\03\20\03{NICKNAME}\03\20\03{LASTNAME}\03\1F\0D\0A{TITLE}\03\1F\0D\0A{COMPANY}\03\1F\0D\0A{ADDRESS1}\03\1F\0D\0A{CITY}\03\20\03{STATE}\03\20\03{ZIPCODE}\03\1F\0D\0A{COUNTRY}\03\1F\0D\0A{PHONE}\03\1F\0D\0A{FAX}\03\1F\0D\0A{EMAIL}\03\1F\0D\0A\0D\0A\0D\0A\1A | |
// or | |
// {SHOW_CODE}^{BADGEID}^{LASTNAME}^{FIRSTNAME}^{TITLE}^{COMPANY}^{ADDRESS1}^{ADDRESS2}^{CITY}^{STATE}^{ZIPCODE}^{COUNTRY}^{PHONE}^{FAX}^{EMAIL}^{REG_TYPE}^{CATEGORY}^{SPECIALTY}^{RANK}^{COMPANY2}^{ADDRESS3}^{ADDRESSTYPE}^ | |
// Match the fields: {field_name} and group(1) has field_name | |
Pattern pattern = Pattern.compile("\\{(\\w*)\\}"); | |
Matcher matcher = pattern.matcher(str); | |
JSONArray array = new JSONArray(); | |
// Store each field name in the JSONArray | |
while (matcher.find()) { | |
// There's only a single group; group(0) is the whole thing | |
array.put(matcher.group(1)); | |
} | |
final String fieldJson = array.toString(); | |
new StorePreferenceTask(context).execute( | |
PreferenceHelper.PREF_BADGE_LAYOUT_FIELDS, fieldJson); | |
// Replace each \ with \x | |
String regex = str.replaceAll("\\\\", "\\\\x"); | |
// and replace ^ with \^ | |
regex = regex.replaceAll("\\^", "\\\\^"); | |
// Replace the field names with ([\x20-x99]*?); this matches most | |
// non-control characters in a non-greedy way, and so replaces the | |
// {FIRSTNAME} with {[\x20-x99]*?) | |
regex = pattern.matcher(regex).replaceAll("([\\\\x20-\\\\xFF]*?)"); | |
// Add start of string and end of string matchers | |
regex = "^" + regex + "$"; | |
new StorePreferenceTask(context).execute( | |
PreferenceHelper.PREF_BADGE_LAYOUT_REGEX, regex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment