如何用另一用户输入替换用户输入的一部分?

时间:2020-10-01 09:25:05

标签: java regex replace

我正在制作一个必须与cmd一起运行的文本编辑器。用户粘贴要编辑的文本,然后选择要使用的文本。我很难替换掉他们粘贴的文本的一部分。

这是我为编辑器编写的代码的一部分:

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

public class TextEd {
    
    public static void main(String[] args) {
        
        Editor editor = new Editor();
        editor.copiedText();
    }
}
class Editor {
    
    private Scanner scan = new Scanner(System.in);
    private String text = " ";
    
    public void copiedText() {
    
        System.out.println("Paste your text here.");        //The user input
        text = scan.nextLine();
        menu();
    }

    public void menu() {
    
        System.out.println("Welcome to the text editor.\n"
            + "What do you wish to do?\n"
            + "1. Replace a word/line.\n"
            + "2. Exit program.");
        int choice = scan.nextInt();
    
        if (choice == 1) {
            replacing();
        }
        else if (choice == 2) {
            System.exit(0);
        }
    }
}

这是替换部分的代码,我在这里苦苦挣扎:

public void replacing() {    //still not working argh
    
    String replacement = scan.nextLine();
    System.out.println("What dou you want to replace?");
    try {
        Pattern replacepat = Pattern.compile(scan.next());
        Matcher match = replacepat.match(text);
        System.out.println("What dou you want to replace it with?");
        scan.nextLine();
    
        boolean found = false;
        while (match.find()) {
            text = text.replaceAll(replacepat, replacement);
            System.out.println(text);
        }
    }
    catch (Exception e) { 
        System.out.println("There's been an error.");
    }
}

我得到的错误通知我,模式无法转换为字符串-我理解,replaceAll与int一起工作-但我不知道如何获取用户要替换的文本的索引,因为用户的工作是先粘贴文本,然后粘贴要替换的文本的另一部分。

1 个答案:

答案 0 :(得分:1)

replaceAll将第一个参数编译为正则表达式(请参见javadoc) 因此,您只需提供正则表达式作为字符串即可:

public void replacing() {    //still not working argh
    
    System.out.println("What dou you want to replace?");
    try {
        String findText=scan.next();
        System.out.println("What dou you want to replace it with?");
        String newText=scan.next();
    
        text = text.replaceAll(findText, newText);
        System.out.println(text);
    }
    catch (Exception e) { 
        System.out.println("There's been an error.");
    }
}

来自javadoc:

An invocation of this method of the form str.replaceAll(regex, repl) yields 
exactly the same result as the expression 

java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl) 
相关问题