Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extract the no. 2 digit from string into integer?

Tags:

java

In my case ,the users can input

f 0 ,f 1, f 2//1 digit
p 0, p 1 ,p 2//1 digit
j 0 1, j 0 2, j 1 0....(any combination of 0,1,2) //2 digits
q ,Q //for quit

I use

      str = scanner.nextLine();//get the whole line of input
 if(str.matches("[fpjq]\\s[012]"))......//check vaild input
             char1=str .charAt(0);//get the first letter

Then I want to get the next digit now .

Any string method can extract the next digit from string into Int format?

However ,some bugs still exist for my method . For example , it can quit the program for QQ or qq or q+any letters

Any better methods can be provided?

edit

for example p 0 1 char1=str .charAt(0);//get p now I want to get 0 and 1 and store into int

like image 955
evabb Avatar asked Oct 30 '22 16:10

evabb


1 Answers

You can use capturing groups (...) in your regex to extract parts of the matched data:

str = scanner.nextLine();
Pattern regex = Pattern.compile("^([fpjq])(?:\\s+([012]))?(?:\\s+([012]))?$");
Matcher matcher = regex.matcher(str.trim());
if (matcher.find()) {
    String letter = matcher.group(1);
    String digit1 = matcher.group(2); // null if none
    String digit2 = matcher.group(3); // null if none
    // use Integer.parseInt to convert to int...
} else {
    // invalid input
}
like image 182
qxz Avatar answered Nov 09 '22 06:11

qxz