简体   繁体   English

Java从字符串中删除多个字符

[英]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. 我正在玩字符串操作,并且我想做这样的事情,当用户键入课程名称:Windows Server时,该程序应删除Windows加空格字符并仅显示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. 但是现在我想删除多个字符,例如Linux和Unix。 How would I include in my regex Linux and Unix? 如何在我的regex Linux和Unix中使用?

If the user would type in Linux Administration, the program should display Administration only. 如果用户输入Linux Administration,则该程序应仅显示Administration。

To remove only the first word your regex would ^\\w+\\s 要仅删除第一个单词,您的正则表达式将^\\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 \\w+查找1个或多个非空格字符,不要贪婪,因此请在找到匹配项后立即停止
  3. \\s a whitespace character". \\s空格字符”。

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... 您在这里有两个选择...

  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). 创建一个包含要删除的所有术语的Regex术语,我认为类似以下内容的方法可以做到(但我不是Regex专家)。

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

由于您只想删除第一个单词,并假设空格是定界符,因此可以在不使用正则表达式的情况下进行操作:

String newLesson = lesson.substring(lesson.indexOf(" ") + 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM