Saturday, June 12, 2010

String match using Regular expression in both Java and Ruby

sometimes, I will looking for some dynamic data/elements from HTMLsource to make my automation scripts more robust and reliable, so using regular expression to do string match is very useful for me to get them:

Example in Java( for selenium usage):

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {

public static void main(String[] args){


Pattern pattern =
Pattern.compile("information-abc-([0-9]+)");

Matcher matcher =
pattern.matcher("information-abc-9887234-information-abc-223333889-information-abc-12233");

while (matcher.find()) {
for (int i=1; i<=matcher.groupCount(); i++) {
String groupStr = matcher.group(i);
System.out.println(groupStr);
}
}

}
}


Example in Ruby( for Watir usage):

def regex_match(search_pattern)
source_string = "information-abc-9887234-information-abc-223333889-information-abc-12233";

source_string.scan(/#{search_pattern}/) { |match| puts match;}

end

regex_match("information-abc-([0-9]+)");


Love Ruby, it is simple :)

No comments:

Post a Comment