Reputation: 119
public static void main(String[] args) {
String str = "astv*12atthh124ggh*dhr1234sfff123*dgdfg1234*mnaoj";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
List<String> strings = new ArrayList<String>();
List<Integer> nums = new ArrayList<Integer>();
while (m.find()) {
nums.add(Integer.parseInt(m.group()));
}
p = Pattern.compile("[a-z]+");
m = p.matcher(str);
while (m.find()) {
strings.add(m.group());
}
System.out.println(nums);
System.out.println(strings);
}
Output:
[12, 124, 1234, 123, 1234]
[astv, atthh, ggh, dhr, sfff, dgdfg, mnaoj]
But i want output like :
[12124, 1234123, 1234]
[astv, atthhggh, dhrsfff, dgdfg, mnaoj]
Upvotes: 2
Views: 96
Reputation: 31871
To get digit array, you can
*
- Code
String digitArr[] = str.replaceAll("[A-Za-z]", "").split("\\*");
//output
//12124 1234123 1234
You can repeat same thing for getting alphabet array
String stringArr[] = str.replaceAll("[0-9]", "").split("\\*");
//Output
//astv atthhggh dhrsfff dgdfg mnaoj
Upvotes: 1
Reputation: 1096
To keep original regex logic, you can do as follows:
public static void main(String[] args) {
String str = "astv*12atthh124ggh*dhr1234sfff123*dgdfg1234*mnaoj";
List<String> strings = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
Pattern digitPattern = Pattern.compile("\\d+");
Pattern alphaPattern = Pattern.compile("[a-z]+");
String[] splittedArray = str.split("\\*");
for (String nextSplittedString : splittedArray) {
Matcher digitMatcher = digitPattern.matcher(nextSplittedString);
Matcher alphaMatcher = alphaPattern.matcher(nextSplittedString);
String nextDigitAsString = "";
while (digitMatcher.find()) {
nextDigitAsString += digitMatcher.group();
}
if (!nextDigitAsString.isEmpty()) {
nums.add(Integer.parseInt(nextDigitAsString));
}
String nextString = "";
while (alphaMatcher.find()) {
nextString += alphaMatcher.group();
}
if (!nextString.isEmpty()) {
strings.add(nextString);
}
}
System.out.println(nums);
System.out.println(strings);
}
OUTPUT
[12124, 1234123, 1234]
[astv, atthhggh, dhrsfff, dgdfg, mnaoj]
Upvotes: 1
Reputation: 60016
You can use split with *
then you can work with each element for example :
public static void main(String[] args) {
String str = "astv*12atthh124ggh*dhr1234sfff123*dgdfg1234*mnaoj";
String[] spl = str.split("\\*");//[astv, 12atthh124ggh, dhr1234sfff123, dgdfg1234, mnaoj]
List<String> strings = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
for (String s : spl) {
String tmp = s.replaceAll("\\d+", "");//replace all the digits with empty
if (!tmp.trim().isEmpty()) {
strings.add(tmp);
}
tmp = s.replaceAll("[a-z]+", "");//replace all the character with empty
if (!tmp.trim().isEmpty()) {
nums.add(Integer.parseInt(tmp));
}
}
System.out.println(nums);
System.out.println(strings);
}
Output
[12124, 1234123, 1234]
[astv, atthhggh, dhrsfff, dgdfg, mnaoj]
Upvotes: 2