Reputation: 417
I have a String Text . I want to get value of "signature" keyword in Text.
Here is my code with example:
public void parseMethod(){
String Text = "hmac username=\"dhannan\", algorithm=\"hmac-sha1\", headers=\"content\", signature=\"VwjwFaNSw3cLQbuqtwl2XPOmcis=\"";
Pattern pattern = Pattern.compile("signature=\"(.+)\"");
Matcher matcher = pattern.matcher(authorization);
int s = Text.indexOf("signature=");
String data="";
int index=s+11;
while(Text.charAt(index)!='"'){
data+=Text.charAt(index);
index+=1;
}
System.out.println(data);
}
So this will give me output that I want :
VwjwFaNSw3cLQbuqtwl2XPOmcis=
I don't like this method. I want to do in simple like regex or something other way.
By using regex way
Pattern pattern = Pattern.compile("signature=\"(.+)\"");
Matcher matcher = pattern.matcher(Text);
if(matcher.find()){
System.out.println(matcher.group());
}
But it gives this output while I want only value for which I will have to extra work like above:
signature="VwjwFaNSw3cLQbuqtwl2XPOmcis="
Please suggest me an efficient way to do this.
Upvotes: 1
Views: 72
Reputation: 29710
Like 11thdimension suggested, you should use matcher.group(1)
to find the value itself:
String Text = "hmac username=\"dhannan\", algorithm=\"hmac-sha1\", headers=\"content\", signature=\"VwjwFaNSw3cLQbuqtwl2XPOmcis=\"";
Pattern pattern = Pattern.compile("signature=\"(.+)\"");
Matcher matcher = pattern.matcher(Text);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
>> VwjwFaNSw3cLQbuqtwl2XPOmcis=
Upvotes: 1