我正在尝试编写Java RegEx例程,该例程将返回具有以下要求的arraylist”
这是输入:
Az ma9n, 66 a pk0 lan, a c55an*()al: Pan3afffma
这是ArrayList中的预期输出:
Az, ma, 9, n, 66, a, pk, 0, lan, a, c, 55, an, al, Pan, 3, afffma
这是我所拥有的,但还差得远:
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());
最佳答案
如下进行:
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);
}
}
输出:
[Az, ma, 9, n, 66, a, pk, 0, lan, a, c, 55, an, al, Pan, 3, afffma]