我使用replaceAll只列出某个字符串中的数字,我想知道是否有办法限制它被替换的次数。例如:
String s = "1qwerty2qwerty3";
s = s.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(s.trim().split(" ")));
这将过滤掉字符串中的所有数字,得到结果:[1,2,3]。 我想知道是否有办法获得结果[1,2]。所以,基本上该方法找到两个数字并停止。谢谢你的帮助!
答案 0 :(得分:1)
您的replaceAll
正在删除不是数字的所有内容,但您想限制split
返回的数字!相反,我会流式传输split
的结果 - 然后你可以limit
那个和collect
它到List
。像,
String s = "1qwerty2qwerty3";
s = s.replaceAll("\\D+", " "); // <-- equivalent to your current regex.
System.out.println(Stream.of(s.split("\\s+")).limit(2).collect(Collectors.toList()));
输出(根据要求)
[1, 2]
,如果我们在非数字上split
开始,我们实际上可以删除一个步骤。像,
System.out.println(Stream.of(s.split("\\D+")).limit(2)
.collect(Collectors.toList()));
答案 1 :(得分:0)
不要将你不想要的东西分开,而是搜索你想要的东西。
在Java 9+中,这可以通过流轻松完成:
String s = "1qwerty2qwerty3";
System.out.println(Pattern.compile("\\d+")
.matcher(s)
.results()
.limit(2)
.map(MatchResult::group)
.collect(Collectors.toList()));
// or condensed:
System.out.println(Pattern.compile("\\d+").matcher(s).results()
.limit(2).map(r->r.group()).collect(Collectors.toList()));
免责声明:使用来自answer by Elliott Frisch的limit()
的想法。
在Java 5+中,您需要一个find()
循环:
List<String> result = new ArrayList<String>();
for (Matcher m = Pattern.compile("\\d+").matcher(s); m.find(); ) {
result.add(m.group());
if (result.size() == 2)
break;
}
System.out.println(result);
两者的输出
[1, 2]
使用split()
解决方案的优点是,如果输入不是以数字开头,则首先不会获得空字符串。
实施例
String s = "qwerty1qwerty2qwerty3qwerty";
// Using this answer
System.out.println(Pattern.compile("\\d+")
.matcher(s)
.results()
.limit(2)
.map(MatchResult::group)
.collect(Collectors.toList()));
// Using answer by Elliott Frisch
System.out.println(Stream.of(s.split("\\D+")).limit(2)
.collect(Collectors.toList()));
// Alternate, applying comment to answer by Elliott Frisch
System.out.println(Pattern.compile("\\D+")
.splitAsStream(s)
.limit(2)
.collect(Collectors.toList()));
输出
[1, 2]
[, 1]
[, 1]