在Java中用于拆分数字ID的正则表达式:

huangapple go评论97阅读模式
英文:

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 = &quot;1234567890&quot;;
String newStr = &quot;&quot;;
for(int i = 0; i &lt; str.length(); i++) {
	newStr += str.charAt(i);
	if(i % 2 != 0 &amp;&amp; i != str.length() - 1) {
		newStr += &quot;.&quot;;
	}
}
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 = &quot;(?&lt;=\\G..)&quot;;
String str = &quot;1100000000000001&quot;;
String res = Pattern.compile(reg).splitAsStream(str).collect(Collectors.joining(&quot;.&quot;));
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 = &quot;1100000000000001&quot;;
String pattern = &quot;(\\d\\d)(?!$)&quot;;
System.out.println(str.replaceAll(pattern, &quot;$1.&quot;));

huangapple
  • 本文由 发表于 2020年10月9日 00:18:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64266637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定