[英]Replace substrings using regex
所以我一直在嘗試制作這個簡單的加密程序,但我似乎無法弄清楚一些事情。 我需要輸入的短語是
This is a very big morning.
當我輸入它雖然它返回字符串
This is a ag',rery dug>?/ijeb..w ssadorninjeb..w
相反,我回來了
This is a ajedg>P/..w',rery dg>P/ijedg>P/..w ssadorninjedg>P/..w
我不明白為什么以及如何解決它? 我已經學習了大約一個月的java,所以我仍然很新鮮,如果有類似的問題已經得到解答請在那里鏈接我,我將刪除這篇文章。
這是代碼:
import static java.lang.System.out;
import java.util.Scanner;
class Encryption {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
Crypto user1 = new Crypto();
out.print("Please enter in a sentence: ");
String user = userInput.nextLine();
user1.encrypt(user);
out.print(user1.getEncrypt());
}
}
public Crypto() { }
public String myEn;
public void encrypt(String Sentence) {
myEn = Sentence.replaceAll("v","ag',r")
.replaceAll("m" , "ssad")
.replaceAll("g" , "jeb..w")
.replaceAll("b" , "dg>P/");
}
public String getEncrypt() {
return myEn;
}
}
獲得不同輸出的原因是鏈接替換采用先前替換的返回值。 所以在你的情況下,如果有一個v
,它將被改為ag',r
,其中有一個g
。 那g
會觸發replaceAll("g" , "jeb..w")
。
要避免這種情況發生,您應該更改替換的順序:
Sentence.replaceAll("g" , "jeb..w")
.replaceAll("b" , "dg>P/")
.replaceAll("v","ag',r")
.replaceAll("m" , "ssad");
但是,前兩個替換語句無法修復,因為一個替換b
的字符串中包含g
,反之亦然,因此您可能希望更改要替換的字符。
當你更換g
它的替換件包含一個b
所以當你更換b
你得到的所有b
都來自g
替換件也被替換了。 而且對於v
你能做的是
Sentence.replaceAll("g" , "jeb..w")
.replaceFirst("b" , "dg>P/") // as no g's before b's and only want to replace the first
.replaceFirst("v","ag',r")
.replaceFirst("m" , "ssad");
但這只適用於這一句話。
你能做什么:
首先,您應該使用replace()
,而不是replaceAll()
。 兩者都替換找到的所有匹配項,但replaceAll()使用正則表達式匹配,而replace()使用純文本。
接下來,您的替換方式會相互妨礙,因此請使用StringBuffer並從第八個開始,然后向后結束,一次替換一個字符。
解密同樣應該從左邊開始一次處理一個字符。
正如其他人已經告訴過你的問題是你在幾次迭代中替換字符(replaceAll調用)而不是一次。 如果你想防止器皿用於代替你可以使用其他字符替換字符appendReplacement
和appendTail
從Matcher
類。
這是你如何做到這一點
// We need to store somewhere info about original and its replacement
// so we will use Map
Map<String, String> replacements = new HashMap<>();
replacements.put("v", "ag',r");
replacements.put("m", "ssad");
replacements.put("g", "jeb..w");
replacements.put("b", "dg>P/");
// we need to create pattern which will find characters we want to replace
Pattern pattern = Pattern.compile("[vmgb]");//this will do
Matcher matcher = pattern.matcher("This is a very big morning.");
StringBuffer sb = new StringBuffer();// this will be used to create
// string with replaced characters
// lets start replacing process
while (matcher.find()) {//first we need to find our characters
// then pick from map its replacement
String replacement = replacements.get(matcher.group());
// and pass it to appendReplacement method
matcher.appendReplacement(sb, replacement);
// we repeat this process until original string has no more
// characters to replace
}
//after all we need to append to StringBuffer part after last replacement
matcher.appendTail(sb);
System.out.println(sb);
輸出:
This is a ag',rery dg>P/ijeb..w ssadorninjeb..w.
瞧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.