我正在搜索字符串中的州缩写。这是一个示例输入字符串:
String inputStr = 'Albany, NY + Chicago, IL and IN, NY, OH and WI';
我用来匹配州缩写的模式是:
String patternStr = '(^|\\W|\\G)[a-zA-Z]{2}($|\\W)';
我正在遍历匹配项并在循环过程中去除非字母字符,但我知道我应该能够一次性完成。这是当前的方法:
Pattern myPattern = Pattern.compile(patternStr);
Matcher myMatcher = myPattern.matcher(inputStr);
Pattern alphasOnly = Pattern.compile('[a-zA-Z]+');
String[] states = new String[]{};
while (myMatcher.find()) {
String rawMatch = inputStr.substring(myMatcher.start(),myMatcher.end());
Matcher alphaMatcher = alphasOnly.matcher(rawMatch);
while (alphaMatcher.find()) {
states.add(rawMatch.substring(alphaMatcher.start(),alphaMatcher.end()));
}
}
System.debug(states);
|DEBUG|(NY, IL, IN, NY, OH, WI)
这可行,但它很冗长并且可能效率低下。在 Java/Apex 中完成这项工作的一次性方法是什么?