Reputation: 26364
I need a java regex to split the words from the following pattern.
The sentence will start with @ symbol and continue with 6 numerals and then @ symbol. Then 9 numerals and then [ symbol Then 6 numerals and @ symbol Then 2 numerals
There may be space in between the special character and number
For example :
@123456@ 123456789[ 123456@ 12
Here my output should be like :
string1 = 123456
string2 = 123456789
string3 = 123456
string4 = 12
The below regex is not spliting the words properly . Anyone help on this?
@[0-9]{6}@[0-9]{9}[[0-9]{6}@[0-9]{2}
Thanks.
Upvotes: 1
Views: 185
Reputation: 1303
You have an error in your pattern
String s = "@123456@ 123456789[ 123456@ 12";
Pattern p = Pattern.compile("@(\\d{6})@\\s?(\\d{9})\\[\\s?(\\d{6})@\\s?(\\d{2})");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
System.out.println(m.group(4));
}
Upvotes: 1
Reputation: 41838
You can match into capture groups:
Pattern regex = Pattern.compile("^@(\\d{6})@ *(\\d{9})\\[ (\\d{6})@ (\\d{2})");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
String firstGroup = regexMatcher.group(1);
// 123456
String secondGroup = regexMatcher.group(2);
// 123456789
String thirdGroup = regexMatcher.group(3);
// 123456
String fourthGroup = regexMatcher.group(4);
// 12
}
Upvotes: 2
Reputation: 1916
The regex-pattern by which you want to split is: [@\[]\s*
. This overview will help to understand the pattern.
In Java it looks like follows:
String string = "@123456@ 123456789[ 123456@ 12";
String[] strings = string.split("[@\\[]\\s*");
The strings
array will contain the desired output [123456,123456789,123456,12]
Upvotes: 1
Reputation: 1236
You must use (...)
to incapsulate "capturing".
@([0-9]{6})@([0-9]{9})\[([0-9]{6})@([0-9]{2})
Upvotes: 1
Reputation: 11051
You can simply use String.split()
!
{
String[] strArr = "@123456@ 123456789[ 123456@ 12".split("[@\\[] ?");
string1 = strArr[0];
string2 = strArr[1];
string3 = strArr[2];
string4 = strArr[3];
}
Online Demo STDOUT:
123456
123456789
123456
12
Upvotes: 1
Reputation: 2191
If you are not sure about the spaces, add them with the * quantity to have 0 to unlimited. And make sure to escape the [
@[0-9]{6}@ *[0-9]{9}\[ *[0-9]{6}@ *[0-9]{2}
Works fine in the RegEx-Tester http://erik.eae.net/playground/regexp/regexp.html
Upvotes: 0
Reputation: 95978
Try this one:
@[0-9]{6}@\s[0-9]{9}\[\s[0-9]{6}@ [0-9]{2}
You should quote the actual [
and add the spaces you want.
See this working example.
Upvotes: 0