wsyy
asked on
Java regex needed
Hi,
How can I use the attached code to extract "B004UJLUQU" from "dp/B004UJLUQU"?
The attached code returns the first matched string, and has been very helpful in the past such that I don't want to change it.
Thanks
How can I use the attached code to extract "B004UJLUQU" from "dp/B004UJLUQU"?
The attached code returns the first matched string, and has been very helpful in the past such that I don't want to change it.
Thanks
public static String extractRegex(String source, String regex){
Pattern re = Pattern.compile(regex, Pattern.DOTALL|Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(source);
while (m.find())
return m.group(0);
return null;
}
Why wouldnot you use "B004UJLUQU" as the pattern:
public static String extractRegex(String source, String regex){
Pattern re = Pattern.compile("B004UJLUQU", Pattern.DOTALL|Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(source);
while (m.find())
return m.group(0);
return null;
}
I tested this:
Output:
String source = "dp/B004UJLUQU";
//public static String extractRegex(String source, String regex){
Pattern re = Pattern.compile("/(.+)$", Pattern.DOTALL|Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(source);
while (m.find())
System.out.println(m.group(1));
// return null;
Output:
B004UJLUQU
This is as a method, though I changed group(0) to group(1):
Output:
public static String extractRegex(String source, String regex){
Pattern re = Pattern.compile(regex, Pattern.DOTALL|Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(source);
while (m.find())
return m.group(1);
return null;
}
public static void main(String[] args){
String source = "dp/B004UJLUQU";
String regex = "/(.+)$";
System.out.println(extractRegex( source, regex));
}
Output:
B004UJLUQU
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
CEH, I don't want to change group(0) in the method.
for_yan, the last method you provided works. can you please explain it a little bit?
I guess that (?<=/) removes the "/", but I don't understand the ".+$" part.
for_yan, the last method you provided works. can you please explain it a little bit?
I guess that (?<=/) removes the "/", but I don't understand the ".+$" part.
.+ this maens any charcter any tnumber of times but at least once
$ - means the end of the string
$ - means the end of the string
So it looks for the slash and then picks up anything after the slash to th end of the string
and this is called positive lookbehind (?<=/) - it checks that ther is a slash before , but does not include it into match
ASKER
Many thanks!
Open in new window