Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex return contiguous words and numbers into arraylist

Tags:

java

regex

I am trying to write a Java RegEx routine that will return an arraylist with the following requirements"

  1. Remove special characters
  2. Add a String to the arraylist of contiguous alpha characters and contiguous numeric characters.
  3. A space or series of spaces is the delimiter.

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());
like image 781
nikotromus Avatar asked Jul 02 '26 10:07

nikotromus


1 Answers

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]
like image 85
Arvind Kumar Avinash Avatar answered Jul 04 '26 22:07

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!