簡體   English   中英

從字符串中的括號中刪除多余的字母和數字

[英]remove extra letters and numbers from parenthesis in a string

我有一個像這樣的字符串:

(aeiou 123) word one

如何從括號中刪除所有內容,以便只保留“一字”?

您可以使用正則表達式,例如:

String str = "(aeiou 123) word one";
str = str.replaceAll("\\([^\\)]*\\)", "").trim();
public class ParanthesisRemoval {

public static void main(String args[])
{
    String test="ab(xy)cd(zw)ef";

    boolean modified = true;
    while(modified)
    {
        modified = false;
        int indexOpenParanthesis = test.indexOf("(");
        int indexClosedParanthesis = test.indexOf(")");
        if(indexOpenParanthesis!=-1 && indexClosedParanthesis!=-1 && indexOpenParanthesis<indexClosedParanthesis)
        {
            int stringLength = test.length();
            test = test.substring(0, indexOpenParanthesis)+test.substring(indexClosedParanthesis+1, stringLength);
            modified=true;
        }

    }

    System.out.println(test);
}

}

請注意,這不適用於嵌套的括號 - (()) 或括號未正確配對 (()

暫無
暫無

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

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