I'm playing with string manipulation and I would like to do something like this, when a user types the lesson name: Windows Server, the program should remove Windows plus white space character and display only Server. I managed to do this using this code:
Scanner in = new Scanner(System.in);
String lesson;
System.out.println("Input lesson name: ");
lesson = in.nextLine();
String newLesson = lesson.replaceAll("Windows\\s+", "");
System.out.println("New Lesson is " + newLesson);
But now I want to remove multiple characters like Linux and Unix. How would I include in my regex Linux and Unix?
If the user would type in Linux Administration, the program should display Administration only.
To remove only the first word your regex would ^\\w+\\s
This says:
^
match from the start of the string only \\w+
Find 1 or more non-whitespace characters, do not be greedy so stop as soon as you find a match for \\s
a whitespace character". If I understood the question, try:
String newLesson = lesson.replaceAll("(Windows|Linux|Unix)\\s+", "");
Output:
Input lesson name:
Linux Administration
Administration
You have two options here...
Create a Regex term that encompasses all the terms you want to remove, I think something like the below would do it (but I'm no Regex expert).
replaceAll("(Windows|Linux|Unix)\\\\s+", "");
Store the words you want to remove in a list then cycle through it, removing each term.
List<String> terms = new ArrayList<>(Arrays.asList{"Windows\\\\s+", "Linux\\\\s+", "Unix\\\\s+"}); for(String term : terms) { lesson = lesson.replaceAll(term, ""); }
由于您只想删除第一个单词,并假设空格是定界符,因此可以在不使用正则表达式的情况下进行操作:
String newLesson = lesson.substring(lesson.indexOf(" ") + 1);
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.