Reputation: 1922
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.
Upvotes: 1
Views: 17606
Reputation: 213193
Since you just want to remove first word, and assuming that space is the delimiter, you can do it without regex:
String newLesson = lesson.substring(lesson.indexOf(" ") + 1);
Upvotes: 1
Reputation: 1277
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, "");
}
Upvotes: 1
Reputation: 34146
If I understood the question, try:
String newLesson = lesson.replaceAll("(Windows|Linux|Unix)\\s+", "");
Output:
Input lesson name:
Linux Administration
Administration
Upvotes: 2
Reputation: 41168
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".Upvotes: 1