Javaでの文字列のReplace()およびreplaceAll()

public String replaceAll(String regex、String replace)

  • replaceAllは、regexの正規表現に従って置き換えられます
  • 通常の式:文字列として指定し、最初にこのクラスのインスタンスにコンパイルする必要があります。結果のパターンを使用して、任意の文字
    シーケンスおよび通常の式に一致できるMatcherオブジェクトを作成できます通常の式はより複雑で、多くの一致ルールが定義されています。

public String replace(CharSequence target、CharSequence replace)

  • replaceは、置き換える文字に基づいています

例えば:

public class DefangingAnIpAddress {
    
    
	public static void main(String[] args) {
    
    
		defangIPaddr("1.1.1.1");
	}

	static public String defangIPaddr(String address) {
    
    
		if (address.length() == 0) {
    
    
			return address;
		}
		System.out.println(address.replaceAll("\\.", "[.]"));
		System.out.println(address.replace(".", "[.]"));
		return address.replace(".", "[.]");
	}
}

replaceAllを使用する場合、シンボル(事前定義された文字クラス)をエスケープする必要があります(「\」を使用)。

おすすめ

転載: blog.csdn.net/weixin_44998686/article/details/108858491