亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從開頭和結尾刪除非字母數字字

從開頭和結尾刪除非字母數字字

素胚勾勒不出你 2022-06-15 14:47:02
當我從數據庫表中獲取字符串時,下面給出的字符串。#$%^&*\n\r\t公司;姓名; xyz; 美國廣播公司;pqr; \t\r@#$()-上面的示例字符串開頭和結尾有非字母數字字符,所以我想刪除給定字符串的所有非字母數字粗體字符開頭和結尾用簡單的語言我想要這個字符串:“公司;名稱;xyz;abc;pqr; ”
查看完整描述

2 回答

?
慕蓋茨4494581

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;]+$", ""));


查看完整回答
反對 回復 2022-06-15
?
子衿沉夜

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]


查看完整回答
反對 回復 2022-06-15
  • 2 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號