簡體   English   中英

如何替換java中包含任何整數的子串?

[英]How to replace substrings that contain any integer in java?

如何替換形式為“:[number]:”的java中的子字符串

例:

string="Hello:6:World"

更換后,

HelloWorld
ss="hello:909:world"; 

做如下:

String value = ss.replaceAll("[:]*[0-9]*[:]*","");

您可以使用正則表達式來定義所需的模式

String pattern = "(:\d+:)";
string EXAMPLE_TEST = ':12:'
System.out.println(EXAMPLE_TEST.replaceAll(pattern, "text to replace with"));

應該工作取決於你想要更換什么...

這樣做

String s = ":6:";     
s = s.replaceAll(":", "");

編輯1:問題改變后,應該使用

:\d+:

在Java中

:\\d+:

這也是替換::的答案。

這是你應該使用的正則表達式:

:\d*:

正則表達式可視化

Debuggex演示

這是一個正在運行的JavaCode剪切:

String str = "Hello :4: World";
String s = str.replaceAll(":\\d*:","");
System.out.println(s);

replaceAll的一個問題通常是返回更正的String。 調用replaceAll的字符串對象未被修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM