-1

I want to create the list based on the substring from the string with regex

How to have the java code for extracting those numbers (following #) into the list

For ex list {29,131,48,133,30,136,31} be created from the string below

"Join Type : LEFT OUTER\nCondition : ((((xxxx#29 = yyyy#131) && (zzz#48 = zzz#133)) && (ssss#30 = mm#136)) && (gffd#31 = 170))"

shmosel
  • 49,289
  • 6
  • 73
  • 138
user3603360
  • 123
  • 1
  • 3
  • 10

2 Answers2

4

The conventional way:

List<String> results = new ArrayList<>();
Matcher matcher = Pattern.compile("#(\\d+)").matcher(str);
while (matcher.find()) {
    results.add(matcher.group(1));
}

Java 9+:

List<String> results = Pattern.compile("#(\\d+)")
        .matcher(str)
        .results()
        .map(r -> r.group(1))
        .collect(Collectors.toList());
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

I'm not certain whether or not you intended to exclude the last number. Assuming you do, this process may help:

List<String> numbers = new ArrayList<>();
Matcher matcher = Pattern.compile("#(\\d+)").matcher(yourString);
while(matcher.find()){
numbers.add(matcher.group(1)); // group 0 is the whole string, 1 is first capture group
}
numbers.remove(numbers.size()-1);

From there you can turn them into ints, etc.

JJ Brown
  • 543
  • 6
  • 13