英文:
Regex for splitting a number ID (java)
问题
Sure, here's the translated content:
大家好,我只是想知道如何将一个数字进行分割,比如:
"1100000000000001"
分割成:
"11.00.00.00.00.00.00.01"
可能会使用正则表达式吗?
英文:
Hey everyone just wondering how I would go about splitting a number such as:
"1100000000000001"
to:
"11.00.00.00.00.00.00.01"
Possibly using regex?
答案1
得分: 1
使用正则表达式不是解决这个问题的最佳方法。自己构建字符串是一个简单的方法:
String str = "1234567890";
String newStr = "";
for(int i = 0; i < str.length(); i++) {
newStr += str.charAt(i);
if(i % 2 != 0 && i != str.length() - 1) {
newStr += ".";
}
}
System.out.println(newStr);
英文:
Using a regex is not the best solution for this problem. Constructing the string yourself offers a simple way to do this:
String str = "1234567890";
String newStr = "";
for(int i = 0; i < str.length(); i++) {
newStr += str.charAt(i);
if(i % 2 != 0 && i != str.length() - 1) {
newStr += ".";
}
}
System.out.println(newStr);
答案2
得分: 0
// 分割字符串,每两个字符为一组,然后使用 `.` 作为分隔符连接结果数组中的元素:
String reg = "(?<=\\G..)";
String str = "1100000000000001";
String res = Pattern.compile(reg).splitAsStream(str).collect(Collectors.joining("."));
System.out.println(res);
英文:
Split at every second char and join the elements of the resulting array using .
as a delimeter:
String reg = "(?<=\\G..)";
String str = "1100000000000001";
String res = Pattern.compile(reg).splitAsStream(str).collect(Collectors.joining("."));
System.out.println(res);
答案3
得分: 0
使用正则表达式模式:
String str = "1100000000000001";
String pattern = "(\\d\\d)(?!$)";
System.out.println(str.replaceAll(pattern, "$1."));
英文:
using regex pattern :
String str = "1100000000000001";
String pattern = "(\\d\\d)(?!$)";
System.out.println(str.replaceAll(pattern, "$1."));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论