这是在Java 7中的内容
我不懂正则表达式,所以想知道有没有人知道如何使用split方法从字符串中获取所有用户名:
{tchristofferson=10, mchristofferson=50}
然后将用户名添加到一个String[]数组中?这里只有两个用户名,但我希望它可以适用于无限数量的用户名。
用户名需要遵循以下格式:
3-16个字符,无空格,仅限A-Z大写和小写字母以及0-9数字,唯一的特殊字符是_(下划线)。
这是在Java 7中的内容
我不懂正则表达式,所以想知道有没有人知道如何使用split方法从字符串中获取所有用户名:
{tchristofferson=10, mchristofferson=50}
然后将用户名添加到一个String[]数组中?这里只有两个用户名,但我希望它可以适用于无限数量的用户名。
用户名需要遵循以下格式:
3-16个字符,无空格,仅限A-Z大写和小写字母以及0-9数字,唯一的特殊字符是_(下划线)。
{}
,根据", "
分割字符串,然后根据=
符号分割每个字符串,并取第一项。String input = "{tchristofferson=10, mchristofferson=50}";
List<String> users =
Arrays.stream(input.substring(1, input.length() - 1).split(", "))
.map(s -> s.split("=")[0])
.collect(Collectors.toList());
String[] usernames = str.substring(1)
.split("=\\d+[,}]\\s*");
"=#, "
和"=#}"是我们唯一不想要的东西。如果字符串以"{ tchristofferson=10"
开头,则第一个用户名将获得前导空格。 String input = "{tchristofferson=10, mchristofferson=50}";
Pattern USERNAME_VALUE = Pattern.compile("(\\w+)=(\\d+)");
Matcher matcher = USERNAME_VALUE.matcher(input);
ArrayList<String> list = new ArrayList<>();
while(matcher.find()) {
list.add(matcher.group(1));
}
String[] usernames = list.toArray(new String[0]);
\w
模式(即[a-zA-Z0-9_]
和其他字母数字Unicode码点)。如果您的用户名要求更具限制性或不那么严格,请进行修改。
(\w+)
用于捕获用户名,作为matcher.group(1)
添加到列表中,最终转换为String[]
。
(\d+)
也被用来捕获与此用户相关的数字,作为matcher.group(2)
。目前未使用此捕获组,因此您可以删除括号以获得小的效率收益,即"(\\w+)=\\d+"
。我包含它是为了以防您也想对这些值进行处理。String[] tokens = test.split("[^A-Za-z]");
如果不介意使用List,可以像@Mureinik建议的那样尝试:
List<String> tokens2 = Arrays.stream(test.split("[^A-Za-z]"))
.distinct()
.filter(w -> !w.isEmpty())
.collect(Collectors.toList());
编辑1:
如果列表包含数字,请尝试:
String[] tokens = test.split("[^A-Za-z\w]");
如果您想尝试正则表达式,我强烈推荐这个网站:
[^A-Za-z\\w]
等同于 [^\\w]
,也等同于 \W
。这将输出 ["", "tchristofferson", "10", "", "mchristofferson", "50"]
,其中 ""
、"10"
、""
和 "50"
不是用户名。 - AJNeufeldString str = "tchristofferson=10,mchristofferson=50";
Pattern ptn = Pattern.compile(",");
String[] usernames = ptn.split(str);