Reputation: 3923
I am trying to extract 12 and 15.
AB CD 12 ABC/15 DEF
.*\bAB CD\b\s?(\d+)\s?\bABC\b[/](\d+)\s?\bDEF\b
It is not working as i am not sure how to match exact words. I am trying to match exact words using boundary and it seems to be creating a problem.
I tried
.*\\bAB CD\\b\\s?(\\d+)\\s?\\bABC\\b[/](\\d+)\\s?\\bDEF\\b
.*\\bAB CD\\b\\s*(\\d+)\\s*\\bABC\\b[/](\\d+)\\s*\\bDEF\\b
.*\\bAB CD\\b[\\s]?(\\d+)[\\s]?\\bABC\\b[/](\\d+)[\\s]?\\bDEF\\b
.*\\bAB CD\\b[\\s]*(\\d+)[\\s]*\\bABC\\b[/](\\d+)[\\s]*\\bDEF\\b
thanks.
Upvotes: 0
Views: 291
Reputation: 5012
.*\bAB CD\b\s?(\d+)\s?\bABC\b[/](\d+)\s?\bDEF\b
^^^ ^^ you dont need these \b
Upvotes: 0
Reputation: 135762
Besides the expression being a little redundant, you must be doing something wrong, as your very first expression works:
import java.util.*;
import java.util.regex.*;
import java.lang.*;
class Main {
public static void main (String[] args) throws java.lang.Exception {
String currentLine = "AB CD 12 ABC/15 DEF";
System.out.println("Current Line: "+ currentLine);
Pattern p = Pattern.compile(".*\\bAB CD\\b\\s?(\\d+)\\s?\\bABC\\b[/](\\d+)\\s?\\bDEF\\b");
Matcher m = p.matcher(currentLine);
while (m.find()) {
System.out.println("Matched: "+m.group(1));
System.out.println("Matched: "+m.group(2));
}
}
}
And a demo link to prove: http://ideone.com/0tXFNu
Output:
Current Line: AB CD 12 ABC/15 DEF
Matched: 12
Matched: 15
So make sure you use m.group(NUMBER)
to access each of the matched values.
Upvotes: 1
Reputation: 369064
What you want is just extract digits out of string, try following code:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("AB CD 12 ABC/15 DEF");
while (m.find()) {
System.out.println(m.group());
}
If you want string match exactly except digits:
Pattern p = Pattern.compile("AB\\s+CD\\s+(\\d+)\\s+ABC/(\\d+)\\s*DEF");
Matcher m = p.matcher("AB CD 12 ABC/15 DEF");
if (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Upvotes: 0
Reputation: 89557
You can use this:
"AB\\s*CD\\s*(\\d+)\\s*ABC/(\\d+)\\s*DEF"
Upvotes: 0