问题
i want to get an input from user in string type and find the first 2 numbers and multiply them and replace the result in text the user should put the command word first , the command is : mul example : mul hello 2 car ?7color 9goodbye5 the result should be : 14color 9goodbye5 i wrote this code but its not working can you help me for solving the problem?
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Collusion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String patternString = "((\\d+).+(\\d+))";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(input);
String text = matcher.group(0);
String found = matcher.group(1);
String thirdGroup = matcher.group(2);
String fourthGroup = matcher.group(3);
int firstNum = Integer.parseInt(thirdGroup);
int secondNum = Integer.parseInt(fourthGroup);
int integerMultiple = firstNum * secondNum ;
String multiple = String.valueOf(integerMultiple);
while (matcher.find()) {
String result = text.replace(multiple , found);
System.out.println(result );
}
}
}
回答1:
Do it as follows:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Collusion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the command: ");
String input = scanner.nextLine();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
int count = 0, product = 1, index = 0;
while (m.find() && count != 2) {
product *= Integer.parseInt(m.group());
count++;
if (count == 2) {
index = m.start() + m.group().length();
}
}
System.out.println(product + input.substring(index));
}
}
A sample run:
Enter the command: mul hello 2 car ?7color 9goodbye5
14color 9goodbye5
I also recommend you go through an elegant regex Test Harness program by Oracle to learn more about the effective usage of java.util.regex.Matcher.
来源:https://stackoverflow.com/questions/60606689/regex-example-in-java