gpt4 book ai didi

java - 如何使用单个正则表达式从 Java/Apex 中的匹配子字符串中去除字符?

转载 作者:行者123 更新时间:2023-11-30 11:47:45 35 4
gpt4 key购买 nike

我正在搜索字符串中的州缩写。这是一个示例输入字符串:

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 中完成这项工作的一次性方法是什么?

最佳答案

您需要使用 Matcher.group()。试试这个:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Escaping
{
public static void main(String[] args)
{
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);
StringBuilder states = new StringBuilder();
while (myMatcher.find())
{
states.append(myMatcher.group(2));
states.append(" ");
}

System.out.println(states);
}
}

输出:NY IL IN NY OH WI

在真实系统中,您需要根据所有有效状态缩写的列表进行验证,否则您可能会捡到各种垃圾。

关于java - 如何使用单个正则表达式从 Java/Apex 中的匹配子字符串中去除字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9164172/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com