Getting the data between two square brackets in java from a digital certificate?
Pattern patronValidity = Pattern.compile("Validity: \\[(.*?)\\]");
Matcher matcherValidity = patronValidity.matcher(strCert);
if(matcherValidity.find()){
System.out.println(matcherValidity.group(1));
}
I'm using that to scan a file but it returns no matches. Strangely, the next one does return something, but it's wrong since the left bracket remains in the info.
Pattern patronValidity = Pattern.compile("Validity: (\\[[^]]*)");
Mat开发者_如何学Ccher matcherValidity = patronValidity.matcher(strCert);
if(matcherValidity.find()){
System.out.println(matcherValidity.group(1));
}
This is the value I'm trying to match.
It goes from this as in the file:
Validity: [From: Thu Aug 21 10:22:08 CDT 2008,
To: Sat Aug 21 10:22:08 CDT 2010]
To this as in the output from the second function:
[From: Thu Aug 21 10:22:08 CDT 2008,
To: Sat Aug 21 10:22:08 CDT 2010
The first function doesn't match anything.
Here you go:
Pattern patronValidity = Pattern.compile("\\[([^\\]]+)]");
That should get you what you need!
The reason your first expression doesn't work is because the .
matches everything but new line characters (and possibly others). You need to compile your regex with DOTALL flag set for it to match all characters. For the second, see Josh's answer.
Does it have to be regex? I would probably just use substringing for a problem of this kind.
String str = "Validity: [From: Thu Aug 21 10:22:08 CDT 2008,
To: Sat Aug 21 10:22:08 CDT 2010]";
System.out.println(str.substring(
str.indexOf('[', str.indexOf("Validity: ")),
str.indexOf(']')+1)
);
This should give the wanted output and be much easier to read, update, change or extend. Also I'm not sure how much memory regex uses in Java, but for PHP they recommend the built-in string functions for this kind of work, as the regex engine is much heavier on the system, and there by also slower.
精彩评论