简体   繁体   English

Java RegEx替换

[英]Java RegEx Replacement

I am trying to input a String that contains a single * character, then a second String. 我试图输入一个包含单个*字符的字符串,然后输入第二个String。 The * will be replaced by the second String. *将被第二个字符串替换。

Since the private static String first can not put in the public static void main(String[] args) {} , how do I do the replacement of putting second String in the first String? 由于private static String first不能放在public static void main(String[] args) {} ,我该如何替换将第二个String放在第一个String中?

import java.lang.String;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    private static String a = "*";
    private static String first = first;
    System.out.println("Enter the first String: ");
    String first = scan.nextLine();
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the first String: ");
        String first = scan.nextLine();


        //Second
        System.out.println("Enter the replacement String: ");
        String second = scan.nextLine();
        Pattern p = Pattern.compile(a);
        Matcher m = p.matcher(first);
        first = m.replaceAll(second);
        System.out.println(first);

You don't need to use pattern and matcher here, just plain String#replaceAll method, read about it at the javadocs , as: 您无需在这里使用模式和匹配器,只需使用普通的String#replaceAll方法,即可在javadocs上阅读有关它的信息 ,如下所示:

String a = "\\*";
first = first.replaceAll(a, second);

You just need to escape the * sign, since it is used as regex. 您只需要转义*号,因为它用作正则表达式。

Just to be clear, you can declare and initialize a variables out of the main method, but with the predefined values. 为了清楚起见,您可以在main方法之外声明并初始化变量,但要使用预定义的值。 If you need to initialize a variable via user's input, you have to move your initialization into method's body. 如果需要通过用户输入初始化变量,则必须将初始化移到方法的主体中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM