Java字符串replaceAll()方法
时间:2020-02-23 14:34:32 来源:igfitidea点击:
Java字符串replaceAll()替换所有出现的特定字符,字符串或者字符串中的正则表达式。
该方法返回一个新字符串作为其输出。
该方法需要两个参数。
字符串replaceAll()语法
public String replaceAll(String regex, String replacement)
一个正则表达式,代表替换时要查找的模式以及替换它的替换字符串。
字符串replaceAll()方法可能有多种替换类型。
替换单个字符
要替换单个字符,请指定要替换的字符作为正则表达式。
public class Main { public static void main(String[] args) { String s = "Welcome to theitroad"; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceAll("o","@"); System.out.println("New String: "+rep); } }
Original String: Welcome to theitroad New String: Welc@me t@ J@urnalDev
替换字符序列
要替换字符序列,请在replaceAll()函数中将该序列称为正则表达式。
public class Main { public static void main(String[] args) { String s = "Welcome to theitroad"; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceAll("to","this is"); System.out.println("New String: "+rep); } }
输出
Original String : Welcome to theitroad New String: Welcome this is theitroad
删除/替换空间
replaceAll()方法可以删除或者替换文本字符串中的空格。
public class Main { public static void main(String[] args) { String s = "Welcome to theitroad"; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceAll(" ",""); System.out.println("New String: "+rep); } }
删除空间
Original String : Welcome to theitroad New String: Welcometotheitroad
同样,要替换空白:
public class Main { public static void main(String[] args) { String s = "Welcome to theitroad"; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceAll(" ","_"); System.out.println("New String: "+rep); } }
Original String : Welcome to theitroad New String: Welcome_to_theitroad
隐藏文本中的数字
replaceAll()可以隐藏出现在字符串中的数字。
可用" *"代替数字。
public class Main { public static void main(String[] args) { String s = "Hello! this is the number : 1234 "; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceAll("[0-9]","*"); System.out.println("New String: "+rep); } }
Original String : Hello! this is the number : 1234 New String: Hello! this is the number :
创建自定义消息
replaceAll()可以替换通用字符串中的字符串以生成自定义消息。
让我们从地图中获取值并生成自定义消息。
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { String s = "dear #Employee#, your Current Salary is #Salary#."; Map<String, String> vals = new HashMap<String, String>(); vals.put("#Employee#", "John"); vals.put("#Salary#", "12000"); for (String key : vals.keySet()) { s = s.replaceAll(key, vals.get(key)); } System.out.println(s); } }
dear John, your Current Salary is 12000.
首先替换
与replceAll()不同,replaceFirst()仅替换模式的第一个实例。
public class Main { public static void main(String[] args) { String s = "Welcome to theitroad"; System.out.println("Original String : "+s); System.out.println(); String rep = s.replaceFirst("o","@"); System.out.println("New String: "+rep); } }
Original String: Welcome to theitroad New String: Welc@me to theitroad