简体   繁体   中英

Java RegEx Replacement

I am trying to input a String that contains a single * character, then a second 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?

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 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. If you need to initialize a variable via user's input, you have to move your initialization into method's body.

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.

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