[英]How to replace a specific string in Java?
我通常不求助,但在這里我真的需要幫助。
我有以下代碼示例:
String text = "aa aab aa aab";
text = text.replace("aa", "--");
System.out.println(text);
Console output: -- --b -- --b
我有一個問題,我怎么只替換不AAB包括字符串的AA部分。
所以控制台輸出是:
-- aab -- aab
我有另一個例子:
String text = "111111111 1";
text = text.replace("1", "-");
System.out.println(text);
Console output: --------- -
我只想替換一個角色,而不是所有相同的角色。
所以控制台輸出是:
111111111 -
是否有類似這些情況的Java快捷方式? 我無法弄明白,如何只替換字符串的特定部分。
任何幫助,將不勝感激 :)
您可以使用String.replaceAll(String, String)
的正則表達式 。 通過使用單詞邊界( \\b
),類似於
String[] texts = { "aa aab aa aab", "111111111 1" };
String[] toReplace = { "aa", "1" };
String[] toReplaceWith = { "--", "-" };
for (int i = 0; i < texts.length; i++) {
String text = texts[i];
text = text.replaceAll("\\b" + toReplace[i] + "\\b", toReplaceWith[i]);
System.out.println(text);
}
產出(按要求)
-- aab -- aab
111111111 -
你可以使用正則表達式
String text = "111111111 1";
text = text.replaceAll("1(?=[^1]*$)", "");
System.out.println(text);
說明:
String.replaceAll
與String.replace
相反地采用正則表達式,它取代了一個litteral (?=reg)
正則表達式的右邊部分必須跟一個匹配正則表達式reg
的字符串,但只捕獲正確的部分 [^1]*
表示從0到任意數量不同於'1'
的字符的序列 $
表示到達字符串的結尾 用簡單的英語,這意味着: 請用空字符串替換所有出現的'1'
字符,后跟任意數量的不同於'1'
的字符,直到字符串結尾 。
我們可以使用Java中的StringTokenizer來實現任何類型輸入的解決方案。 以下是示例解決方案,
public class StringTokenizerExample {
/**
* @param args
*/
public static void main(String[] args) {
String input = "aa aab aa aab";
String output = "";
String replaceWord = "aa";
String replaceWith = "--";
StringTokenizer st = new StringTokenizer(input," ");
System.out.println("Before Replace: "+input);
while (st.hasMoreElements()) {
String word = st.nextElement().toString();
if(word.equals(replaceWord)){
word = replaceWith;
if(st.hasMoreElements()){
word = " "+word+" ";
}else{
word = " "+word;
}
}
output = output+word;
}
System.out.println("After Replace: "+output);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.