Dunkey
Dunkey

Reputation: 1922

Java remove multiple characters from string

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

Answers (4)

Rohit Jain
Rohit Jain

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

Michael Hillman
Michael Hillman

Reputation: 1277

You have two options here...

  1. 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+", ""); 
    
  2. 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

Christian Tapia
Christian Tapia

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

Tim B
Tim B

Reputation: 41168

To remove only the first word your regex would ^\w+\s

This says:

  1. ^ match from the start of the string only
  2. \w+ Find 1 or more non-whitespace characters, do not be greedy so stop as soon as you find a match for
  3. \s a whitespace character".

Upvotes: 1

Related Questions