1

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.

4
  • 1
    Do you have a defined list of words to remove? Do you always want to remove the first word? Commented Jan 5, 2014 at 17:29
  • So you just want to display the last word? Or just strip the first word? Pen down some test cases, and possible outcome for that, and from that, come to a definite rule. That would be better to deal with all inputs. Commented Jan 5, 2014 at 17:29
  • @assylias yes I want only to remove the first word Commented Jan 5, 2014 at 17:30
  • @RohitJain yes I want to just strip the first word with my defined list of words, Linux, Unix and Windows Commented Jan 5, 2014 at 17:31

4 Answers 4

2

If I understood the question, try:

String newLesson = lesson.replaceAll("(Windows|Linux|Unix)\\s+", "");

Output:

Input lesson name: 
Linux Administration
Administration
Sign up to request clarification or add additional context in comments.

Comments

1

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".

Comments

1

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, "");
    }
    

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.