I want to get user input for telephone numbers. I have 2 number categories Golden and Normal. When the user enter certain pattern of a telephone number, the system will automatically determine it as Golden or Normal. I'm having problem to code certain pattern. One of the Golden Pattern number is like this: AB001234 where AB is number like 12,23,34,45,56,67,78 and 89. Here what I got so far.
public static void main(String[] args) {
Scanner userinput = new Scanner(System.in);
System.out.println("Enter Telephone Number");
String nophone = userinput.next();
String Golden = "(\\d)(\\1)002345|(\\d*)12345$";
//I want to add AB001234 pattern to the line above but I don't know how.
if (nophone.matches(Golden)) {
System.out.println("Golden");
}
else {
System.out.println("Normal");
}
}
I'm not sure do I really have to use regex or not. One more question, you can see the first part of String Golden is without $ while the second part has $. I'm not sure the effect if I put or remove the $ symbol.
(\\\\d)(\\\\1)
does not check for the sequence like 12
, 23
and so on.. Rather it checks for two smae consecutive digits like 11
, 22
, 33
, ...
To check for sequence, you would have to do it explicitly using Pipe(|)
- (12|23|34|45|...)
So, your pattern for Golden Number
should be like this: -
^(?:12|23|34|45|56|67|78|89)001234$
(?:..)
- Means a non-capturing group
. It will not be captured as a numbered group in your pattern.
NOTE: - If the length of your sequence
is varying, then Regex
is not an appropriate way to match them.
For your second question, $
denotes the end of the string. So, the pattern with $
at the end, will be matched at the end of the string. Also, Caret (^)
is there to match the beginning of the string.
For eg: -
abc$
matches the string "asdfabc"
, but not "sdfabcf"
. ^abc
matches the string "abcfsdf"
, but not "sdfabcf"
. ^abc$
only matches the string "abc"
, because it is the only string, that starts and ends with "abc"
. You can go through the following links to learn more about Regexp
: -
To get this:
AB001234 where AB is number like 12,23,34,45,56,67,78 and 89. Here what I got so far
The regex would look like:
^(12|23|34|45|56|67|78|89)001234$
The $
symbol means end of the string. This means that if there is any aditional character after the last one, the string won't match the Regex.
The ^
symbol means the begining of the string.
For further information, please, check the Summary of regular-expression constructs at the Javadoc API.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.