英文:
Create a Reg-ex which accept numbers and + as the first character
问题
我正在尝试在Java中创建一个正则表达式,以便我可以获得类似于 +82 11-1111-1111
的结果。第一个数字应以 +82
开头,后跟一个空格,然后它只能接受 11
、12
或 13
,其余数字可以接受 0-9
之间的数字。
例如:
+82 12-2234-3344
+82 13-1234-5678
+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.
+82 12-2234-3344
+82 13-1234-5678
+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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论