Reputation: 5
I have variable data and i want to extract a String (containing digits and characters) that is 6 characters long.
Sample_data = YOUR SET ADDRESS IS 6B1BC0 TSTSB NFPSNC92
Sample_data2 = YOUR SET ADDRESS IS 3EC810 P-22A LS02 STA-0213 TSTSA
All Strings of my sample data are variable except "YOUR SET ADDRESS IS"
I need to extract this 6 character long string: "6B1BC0" & "3EC810"
This is what i have tried do far but it isn't returning anything. How do i modify this to return "6B1BC0"
Pattern P = pattern.compile(“YOUR SET ADDRESS IS \\w+ ([A-Z0-9]{6})”);
Matcher n = p.matcher(result);
If(n.find())
{
return n.group(0);
}
Upvotes: 0
Views: 73
Reputation: 92316
You're almost there. Fix your pattern to:
Pattern P = pattern.compile("YOUR SET ADDRESS IS ([A-Z0-9]{6})");
or
Pattern P = pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})");
Working program:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
Pattern p = Pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})");
Matcher n = p.matcher("YOUR SET ADDRESS IS 123456 FOO");
if (n.find()) {
System.out.println(n.group(1)); // Prints 123456
}
}
}
Upvotes: 0
Reputation: 321
Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher m = p.matcher("aTesting123anythingTesting");
if (m.find()) {
System.out.println(m.group(1));
}
Upvotes: 0
Reputation: 39355
Pattern P = pattern.compile(“YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})”);
Upvotes: 1