【问题标题】:How to replace a part of user input with another user input?如何用另一个用户输入替换部分用户输入?
【发布时间】:2020-10-01 09:25:05
【问题描述】:

我正在制作一个必须使用 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.");
    }
}

我收到的错误通知我,Pattern 无法转换为 String - 我理解,replaceAll 可与 int 一起使用 - 但我不知道如何获取用户想要替换的文本的索引,因为用户的工作是粘贴文本,然后粘贴他们要替换的文本的另一部分。

【问题讨论】:

标签: java regex replace


【解决方案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) 

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多