Wednesday, April 8, 2009

Sample to use jave regular expression

Let's say we have a String "optionValueKeys[0]" and we want to split it to a String array {" optionValueKeys","0"}

String fieldName = "optionValueKeys[0]";
if (fieldName.matches("^\\w*\\[\\d*\\]$")) {
String[] splitFieldNameAndIndex = fieldName.split("\\[|\\]");
fieldName = splitFieldNameAndIndex[0];
String indexStr = splitFieldNameAndIndex[1];
index = Integer.parseInt(indexStr);

The first regular expression is to verify the string.
^ is the start of the RE
$ is the end of the RE
\\w means any character
[ and ] need \\ because they are special characters in RE
\\d means any number

The second regular expression is to define the delimiter.
\\[|\\] means the delimiter is [ or ]

No comments:

Post a Comment