使用正则表达式捕获不同的组。 String regex
表达式捕获直到空格为止的所有单词字符。 然后捕获任何字母az或AZ。 然后,如果有空间和其他一些输入,它将捕获并使用它。
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class test {
public static void main(String ar[]) throws java.io.IOException {
String regex = "(\\w*) ([a-zA-Z])( (.*))?";
String str1 = "RM20 A";
String str2 = "RM20 B";
String str3 = "RM20 C this is a user message.";
Pattern pattern = Pattern.compile(regex);
Matcher match1 = pattern.matcher(str1);
Matcher match2 = pattern.matcher(str2);
Matcher match3 = pattern.matcher(str3);
String a;
while (match1.find()) {
a = "Group 1: " + match1.group(1) + "\nGroup 2: " + match1.group(2);
System.out.println(a);
}
System.out.println();
while (match2.find()) {
a = "Group 1: " + match2.group(1) + "\nGroup 2: " + match2.group(2);
System.out.println(a);
}
System.out.println();
while (match3.find()) {
a = "Group 1: " + match3.group(1) + "\nGroup 2: " + match3.group(2) + "\nGroup 4: " + match3.group(4);
System.out.println(a);
}
}
}
>>> Group 1: RM20
>>> Group 2: A
>>> Group 1: RM20
>>> Group 2: B
>>> Group 1: RM20
>>> Group 2: C
>>> Group 4: this is a user message.
您还可以在输入代码中捕获字母/数字:
String regex = "([a-zA-Z]*)(\\d*) ([a-zA-Z])( (.*))?";
String str1 = "RM20 A message thingy";
Pattern pattern = Pattern.compile(regex);
Matcher match1 = pattern.matcher(str1);
while (match1.find()) {
System.out.println(match1.group(1));
System.out.println(match1.group(2));
System.out.println(match1.group(3));
System.out.println(match1.group(5));
}
>>> RM
>>> 20
>>> A
>>> message thingy