I have this line in my output:
current state of: "admin"
I want to remove the double quotes around admin
.
How can I do it using Java? I want to print only admin
.
I have this line in my output:
current state of: "admin"
I want to remove the double quotes around admin
.
How can I do it using Java? I want to print only admin
.
You may try something like:
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);
}
}
Assuming that your pattern is something like current state of: "nameYouWantToExtract"
. You can use a regular expression to extract what matches your pattern:
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));
}
Parenthesis around [a-zA-Z]+
are creating a group, that's why you can extract the value being matched by [a-zA-Z]+
.
You may change it to [a-zA-Z0-9]+
to be able to extract out numbers too, if applicable.
This can be accomplished using regular expressions. The pattern you are interested in matching is:
current state of: \"([a-zA-Z0-9]*)\"
This pattern contains a group (the part surrounded by parenthesis), which we've defined as ([a-zA-Z0-9]*). This matches zero or more characters belonging to sets a-z, A-Z, or 0-9.
We want to remove all occurrences of this pattern from the string and replace them with the values matched by the group within the pattern. This can be done with a Matcher object by repeatedly calling find(), fetching the value matched by the group, and calling replaceFirst to replace the entire matched text with the value of the group.
Here is some example code:
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);
And this is what the output looks like:
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
If there are no double quotes in either the prefix string or the value to extract, then the simplest way to do this is with split
, something like this.
String[] inputSplit = theInput.split("\"");
String theOutput = inputSplit.length > 1 ? inputSplit[1] : null;