gpt4 book ai didi

java - 用于标记电话号码的字符串标记器

转载 作者:行者123 更新时间:2023-12-01 13:29:29 24 4
gpt4 key购买 nike

您能否帮助我将用户输入的电话号码标记为以下格式:xxx xxx-xxxx in the first else if

正则表达式已被验证可以正常工作。我会把它包括在内。

按照与我想要获取的其余电话号码相同的步骤进行操作前 3 位数字放入单独的变量中,其余数字连接起来。

这是代码

else  if (ValidatePhone.validateSpaceAfterAreaCode(input)) {
StringTokenizer st = new StringTokenizer(input);
String token = st.nextToken("\\s").toString();
// firstdigits = new Long(st.nextToken("\\s")).toString();
phoneNumber = new Long(st.nextToken("-")).toString();
phoneNumber += new Long(st.nextToken("-")).toString();
num = Long.parseLong(phoneNumber);
JOptionPane.showMessageDialog(null, "first digits: " + token + "\nlast digits: " + num);
}
//WORKING for xxx.xxx.xxxx

else if (ValidatePhone.validateAllPeriods(input)) {
StringTokenizer st = new StringTokenizer(input);
firstdigits = new Long(st.nextToken(".")).toString();
phoneNumber = new Long(st.nextToken(".")).toString();
phoneNumber += new Long(st.nextToken(".")).toString();
num = Long.parseLong(phoneNumber);
JOptionPane.showMessageDialog(null, "first digits: " + firstdigits + "\nlast digits: " + num);
}

这是验证电话类中的函数

public static boolean validateSpaceAfterAreaCode(String acspace)
{
return acspace.matches("^[1-9]\\d{2}\\s\\d{3}-\\d{4}");
}

最佳答案

你让事情变得比需要的更加复杂。我猜允许的形式是

nnn nnn-nnnn
nnn-nnn-nnnn
nnn.nnn.nnnn

并且您不希望允许其他变体,例如 nnn nnn.nnnnnnn.nnn-nnnn。试试这个

Pattern p1 = Pattern.compile("([2-9]\\d{2})([-.])(\\d{3})\\2(\\d{4})");
Pattern p2 = Pattern.compile("([2-9]\\d{2})(\\s)(\\d{3})-(\\d{4})");

Matcher m = p1.matcher(input);

if (!m.matches())
m = p2.matcher(input)
if (m.matches()
{
// results are in m.group(1), m.group(3) and m.group(4)
}
else
{
// input didn't match
}

说明:

p1
([2-9]\\d{2}) - Areacode (first digit must be 2-9)
([-.]) - Delimiter, either a dot or hyphen
(\\d{3}) - The 3-digit exchange
\\2 - Back-reference to the first delimiter
(\\d{4}) - The 4-digit number

反向引用导致正则表达式匹配第一个分隔符匹配的任何内容。

模式 p2 很简单,只是我在第一个分隔符周围放置了捕获括号,因此数字组的索引在两种情况下都是相同的,从而无需检查哪个模式匹配。

关于java - 用于标记电话号码的字符串标记器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21653454/

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