用字符替换所有数字子串。

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

Replace All numeric substring with character

问题

I have to replace all digit patterns with some character. For 1 digit its working fine for e.g for given string ramesh_gone_to_avbp_9_vc.pdf its working fine changing it to ramesh_gone_to_avbp_*_vc.pdf but for given input ramesh_gone_to_avbp_91_vc.pdf its changing to ramesh_gone_to_avbp_**_vc.pdf but i want output like ramesh_gone_to_avbp_*_vc.pdf

This is what i tried so far

String ss = "ramesh_gone_to_avbp_92_vc.pdf";
System.out.println(ss.replaceAll("(?<=[\\d\\.])-(?=[\\d\\.])", "*"));
英文:

I have to replace all digit patterns with some character. For 1 digit its working fine for e.g for given string ramesh_gone_to_avbp_9_vc.pdf its working fine changing it to ramesh_gone_to_avbp_*_vc.pdf but for given input ramesh_gone_to_avbp_91_vc.pdf its changing to ramesh_gone_to_avbp_**_vc.pdf but i want output like ramesh_gone_to_avbp_*_vc.pdf

This is what i tried so far

String ss = &quot;ramesh_gone_to_avbp_92_vc.pdf&quot;;
System.out.println(ss.replaceAll(&quot;(?&lt;=[\\d\\.])-(?=[\\d\\.])&quot;, &quot;*&quot;));

答案1

得分: 1

你可以简单地匹配\d+,它匹配一个或多个数字组:

String ss = "ramesh_gone_to_avbp_92_vc.pdf";
String output = ss.replaceAll("\\d+", "*");
System.out.println(output);  // ramesh_gone_to_avbp_*_vc.pdf
英文:

You may simply match on \d+, which matches groups of numbers of one or more digits:

<!-- language: java -->

String ss = &quot;ramesh_gone_to_avbp_92_vc.pdf&quot;;
String output = ss.replaceAll(&quot;\\d+&quot;, &quot;*&quot;);
System.out.println(output);  // ramesh_gone_to_avbp_*_vc.pdf

huangapple
  • 本文由 发表于 2023年6月8日 11:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428377.html
匿名

发表评论

匿名网友

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

确定