繁体   English   中英

如何从Java中的字符串中删除特定模式?

[英]How to remove a particular pattern from a String in Java?

我的输出中有这行:

current state of: "admin" 

我想删除admin周围的双引号。

如何使用Java做到这一点? 我只想打印admin

您可以尝试以下方法:

public class Main {
    public static void main(String[] args) {
        String outputLine = "current state of: \"admin\"";

        outputLine = outputLine.substring(19, outputLine.length() - 1);
        System.out.print(outputLine);
    }
}

假设您的模式类似于current state of: "nameYouWantToExtract" 您可以使用正则表达式提取与您的模式匹配的内容:

Pattern p = Pattern.compile("^current state of: \"([a-zA-Z]+)\"$");
Matcher m = p.matcher("current state of: \"nameYouWantToExtract\"");

if (m.find()) {
    System.out.println(m.group(1));
}

围绕[a-zA-Z]+括号将创建一个组,这就是为什么您可以提取与[a-zA-Z]+匹配的值的原因。

您也可以将其更改为[a-zA-Z0-9]+ ,以便也可以提取数字。

进一步了解正则表达式

这可以使用正则表达式来完成。 您感兴趣的匹配模式是:

current state of: \"([a-zA-Z0-9]*)\"

此模式包含一个组(用括号括起来的部分),我们将其定义为([a-zA-Z0-9] *)。 这与属于集合z,AZ或0-9的零个或多个字符匹配。

我们要从字符串中删除所有出现的该模式,并将其替换为模式中组所匹配的值。 可以通过重复调用find(),获取与该组匹配的值,然后调用replaceFirst用该组的值替换整个匹配的文本,来使用Matcher对象来完成此操作。

这是一些示例代码:

Pattern pattern = Pattern.compile("current state of: \"([a-zA-Z0-9]*)\"");

String input = "the current state of: \"admin\" is OK\n" + 
               "the current state of: \"user1\" is OK\n" + 
               "the current state of: \"user2\" is OK\n" + 
               "the current state of: \"user3\" is OK\n";

String output = input;
Matcher matcher = pattern.matcher(output);
while (matcher.find())
{
    String group1 = matcher.group(1);
    output = matcher.replaceFirst(group1);
    matcher = pattern.matcher(output);      // re-init matcher with new output value
}

System.out.println(input);
System.out.println(output);

这是输出的样子:

the current state of: "admin" is OK
the current state of: "user1" is OK
the current state of: "user2" is OK
the current state of: "user3" is OK

the admin is OK
the user1 is OK
the user2 is OK
the user3 is OK

如果前缀字符串或要提取的值中都没有双引号,那么最简单的方法是使用split ,类似这样。

String[] inputSplit = theInput.split("\"");
String theOutput = inputSplit.length > 1 ? inputSplit[1] : null;

暂无
暂无

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

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