簡體   English   中英

無法使用正則表達式在java中用另一個字符串替換一個字符串

[英]Unable to replace a string with another string in java using regex

我有一個字符串,想替換其中的某些字符。 輸入String = "abc test=0 test1=123 test2=764"輸出String = "abc test=$test test1=$test1 test2=$test2"

我在 java 中使用 replace 和 replaceAll 嘗試了一些事情。 例如:

String abc = directiveValue.replaceAll("test%", test+"=$"+test);

要么

String abc = directiveValue.replaceAll("test[.*]", test+"=$"+test);

你可以匹配:

(test\d*)=\S*

正則表達式演示

並替換為 2 個捕獲組$1=\$$1之間的美元符號

System.out.println(
    "abc test=0 test1=123 test2=764"
        .replaceAll(
          "(test\\d*)=\\S*",
          "$1=\\$$1"
        )
);

輸出

abc test=$test test1=$test1 test2=$test2

我們可以使用正則表達式替換:

String input = "abc test=0 test1=123 test2=764";
String output = input.replaceAll("(\\w+)=\\w+", "$1=\\$$1");
System.out.println(output);

// abc test=$test test1=$test1 test2=$test2

使用 VScode,我將使用這個(test)(\d?)(=)(\b.+?\b)
並替換為$1$2$3$test$2

我希望它對您的 Java 實現有所啟發。 :)

暫無
暫無

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

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