[英]Splitting A String In Java?
这是在Java 7中
我不知道正则表达式,所以我想知道是否有人知道如何使用split方法从字符串中获取所有用户名:
{tchristofferson=10, mchristofferson=50}
然后将用户名添加到String []数组? 这些只是两个用户名,但我希望这可以用于无穷无尽的用户名。
用户名需要以下格式:
3-16个字符,没有空格,AZ大写和小写0-9,只有特殊字符是_(下划线)。
这看起来像JSON,所以“正确”的答案可能是使用JSON解析器。 如果这不是一个选项,你可以删除封闭的{}
,根据", "
拆分字符串,然后根据=
符号拆分每个字符串,取第一项:
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"
,则第一个用户"{ tchristofferson=10"
获得前导空格。
更好的方法是匹配你想要的东西。 现在我不想在iPhone屏幕上创建答案,这里是:
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+"
。 我把它包括在内,以防你想对这些值做些什么。
只要没有(^)一个单词(A-Za-z),你就可以尝试拆分:
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]”);
如果你想试用正则表达式,我强烈推荐这个网站:
如果用户名包含数字和特殊字符,例如= then:
String str = "tchristofferson=10,mchristofferson=50";
Pattern ptn = Pattern.compile(",");
String[] usernames = ptn.split(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.