I am trying to write a Java RegEx routine that will return an arraylist with the following requirements"
Here is the input:
Az ma9n, 66 a pk0 lan, a c55an*()al: Pan3afffma
Here is the expected output of what should be in the ArrayList:
Az, ma, 9, n, 66, a, pk, 0, lan, a, c, 55, an, al, Pan, 3, afffma
Here is what I have but it's not even close:
String test = "Az ma9n, 66 a pk0 lan, a c55an*()al: Pan3afffma";
List<String> list = new ArrayList<String>();
test = test.replaceAll("[^a-zA-Z0-9|\\s]", "");
Matcher m = Pattern.compile("[a-z+A-Z+0-9+]").matcher(test);
while(m.find()) {
list.add(m.group());
}
System.out.println(list.toString());
Do it as follows:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String test = "Az ma9n, 66 a pk0 lan, a c55an*()al: Pan3afffma";
List<String> list = new ArrayList<String>();
// Pattern to match either sequence of digits or that of letters
Pattern pattern = Pattern.compile("[0-9]+|[A-Za-z]+");
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
list.add(matcher.group());
}
// Display list
System.out.println(list);
}
}
Output:
[Az, ma, 9, n, 66, a, pk, 0, lan, a, c, 55, an, al, Pan, 3, afffma]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With