我的输出中有这一行:
current state of: "admin"
我想删除admin
周围的双引号。
我怎样才能使用Java?我只想打印admin
。
答案 0 :(得分:2)
您可以尝试以下方式:
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);
}
}
答案 1 :(得分:2)
假设您的模式类似于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]+
,以便能够提取数字(如果适用)。
答案 2 :(得分:1)
这可以使用正则表达式来完成。您有兴趣匹配的模式是:
current state of: \"([a-zA-Z0-9]*)\"
该模式包含一个组(括号括起的部分),我们将其定义为([a-zA-Z0-9] *)。这匹配属于集合a-z,A-Z或0-9的零个或多个字符。
我们希望从字符串中删除所有出现的此模式,并将其替换为模式中组所匹配的值。这可以通过重复调用find()获取Matcher对象,获取组匹配的值,并调用replaceFirst以将整个匹配文本替换为组的值来完成。
以下是一些示例代码:
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
答案 3 :(得分:0)
如果前缀字符串或要提取的值中没有双引号,那么最简单的方法是使用split
,就像这样。
String[] inputSplit = theInput.split("\"");
String theOutput = inputSplit.length > 1 ? inputSplit[1] : null;