java如何用另一个用户输入替换一部分用户输入?
我正在制作一个文本编辑器,它必须运行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 楼答案
replaceAll将第一个参数编译为正则表达式(参见javadoc) 所以你只需要提供正则表达式作为字符串:
来自javadoc: