Wednesday, January 22, 2014

Extract value from string using regex in java

So suppose you want to extract values from a string based on a certain regex pattern. The thing that i didn't know was that I needed to use () around the data I wanted to capture.

import java.util.regex.*
Pattern p = Pattern.compile("(.*)/post/(.*)");
def str = "http://home.com/post/56"
Matcher m = p.matcher(str);
if (m.find()) {
println m.group(1);
println m.group(2);
}
view raw gistfile1.java hosted with ❤ by GitHub

Output
http://home.com
56

I dedicate this post to all laymen out there, who get confused with coding and stuff

No comments:

Post a Comment