2 回答

TA貢獻1850條經驗 獲得超11個贊
你可以這樣做:
String example="#$%^&*\n\r\t company; name; xyz; abc; pqr; \t\r@#$()-";
String result = example.replaceAll("(^[^\\w;]+|[^\\w;]+$)", "");
System.out.println(result);
它打?。?/p>
公司; 姓名; xyz; 美國廣播公司;pqr;
它可以用兩個替換來替換 - 用于字符串的開頭,然后用于結尾:
String result=example.replaceAll("^[^\\w;]+", "").replaceAll("[^\\w;]+$", ""));

TA貢獻1828條經驗 獲得超3個贊
正則表達式的另一種方法是遍歷字符串的字符,然后找出第一個分別最后遇到的字母數字值的開始和結束索引:
public static String trim(String input) {
int length = input.length(), start = 0, end = length;
// iterate from the start
// until the first alphanumeric char is encountered
while (start < length && notAlphaNumeric(input.charAt(start++))) {}
start--;
// iterate from the end
// until the first alphanumeric char is encountered
while (0 < end && notAlphaNumeric(input.charAt(--end))) {}
end++;
// return the original string if nothing has changed
if (start == 0 && end == length) return input;
// return an empty string if the indices passed one another
if (start >= end) return "";
// else return the substring from start to end
return input.substring(start, end);
}
private static boolean notAlphaNumeric(char c) {
return c != ';' && (c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z');
}
我定義為字母數字的值與此正則表達式組匹配:[;0-9a-zA-Z]
添加回答
舉報