创建一个正则表达式,它可以接受数字和 + 作为第一个字符。

huangapple go评论82阅读模式
英文:

Create a Reg-ex which accept numbers and + as the first character

问题

我正在尝试在Java中创建一个正则表达式,以便我可以获得类似于 +82 11-1111-1111 的结果。第一个数字应以 +82 开头,后跟一个空格,然后它只能接受 111213,其余数字可以接受 0-9 之间的数字。

例如:

  1. +82 12-2234-3344
  2. +82 13-1234-5678
  3. +82 11-3456-4567
英文:

I am trying to create a regex where I get the results as +82 11-1111-1111 in java. The first number should start with +82 with a space then it should get accept only 11 or 12 or 13 and the n the rest of the numbers can accept numbers between 0-9

For eg.

  1. +82 12-2234-3344
  2. +82 13-1234-5678
  3. +82 11-3456-4567

Please help

答案1

得分: 1

我认为你应该尝试类似这样的写法:

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

public class PhoneNumberRegex {
    public static void main(String[] args) {
        System.out.println(validate("+82 12-2234-3344"));
        System.out.println(validate("+82 13-1234-5678"));
        System.out.println(validate("+82 11-3456-4567"));
        System.out.println(validate("+82 31-3456-4567"));
        System.out.println(validate("+82 31-34564-4567"));
    }
    
    private static boolean validate(String input) {
        Pattern argPattern = Pattern.compile("\\+82 (12|13|11)(?:-\\d{4}){2}");
        Matcher matcher = argPattern.matcher(input);
        return matcher.matches();
    }
}

当我运行这段代码时,得到如下输出:

src : $ java PhoneNumberRegex 
true
true
true
false
false
英文:

I think you should try something like this:

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

public class PhoneNumberRegex {
    public static void main(String[] args) {
        System.out.println(validate("+82 12-2234-3344"));
        System.out.println(validate("+82 13-1234-5678"));
        System.out.println(validate("+82 11-3456-4567"));
        System.out.println(validate("+82 31-3456-4567"));
        System.out.println(validate("+82 31-34564-4567"));
    }
    
    private static boolean validate(String input) {
        Pattern argPattern = Pattern.compile("\\+82 (12|13|11)(?:-\\d{4}){2}");
        Matcher matcher = argPattern.matcher(input);
        return matcher.matches();
    }
}

When I run this, I get this output:

src : $ java PhoneNumberRegex 
true
true
true
false
false

huangapple
  • 本文由 发表于 2020年10月14日 23:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64357193.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定