【问题标题】:regex example in javajava中的正则表达式示例
【发布时间】:2020-03-09 18:53:23
【问题描述】:

我想从用户那里获取字符串类型的输入 并找到前 2 个数字并将它们相乘并将结果替换为文本 用户应该把命令字放在前面,命令是:mul 例如: mul hello 2 car ?7color 9goodbye5 结果应该是:14color 9goodbye5 我写了这段代码,但它不工作 你能帮我解决这个问题吗?

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 );

            }
        }
    }

【问题讨论】:

标签: java regex string stringbuilder


【解决方案1】:

按如下方式进行:

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));
    }
}

示例运行:

Enter the command: mul hello 2 car ?7color 9goodbye5
14color 9goodbye5

我还建议您通过 Oracle 的优雅正则表达式 Test Harness 程序来了解更多关于有效使用 java.util.regex.Matcher 的信息。

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 2015-04-27
    • 2013-09-17
    • 2016-09-28
    相关资源
    最近更新 更多