日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android如何使用正則表達式只保留字母數字_Android

作者:最孤單的人 ? 更新時間: 2022-07-25 編程語言

前言

正則表達式是對字符串操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個“規則字符串”,這個“規則字符串”用來表達對字符串的一種過濾邏輯。

#1. 匹配字母(大寫/小寫)和數字的字符

正則表達式:[^a-zA-Z0-9]

#2. 使用正則表達式,將給定的字符串進行處理,只保留字母和數字:

我們需要將非字母和數字進行替換空替換,即需要匹配非字母和數字,

正則表達式為: [^a-zA-Z0-9]

/**
 * 刪除特殊字符并僅顯示字母數字字符:
 * 沒有破折號,沒有散列,沒有崩潰或斜線,沒有空格,等等
 *
 * @return 字符串只有字母數字字符
 */
fun String.formatToAlphanumeric(): String = this.replace("[^a-zA-Z0-9]*".toRegex(), "")

#3. 添加單元測試:

    @Test
    fun formatToAlphanumericTest() {
        val expectedString  = "33K212A"
        val stringWithDash = "33K-21-2A"
        val stringWithSpace = "33-K21 2A "
        assertEquals(expectedString, stringWithDash.formatToAlphanumeric())
        assertEquals(expectedString, stringWithSpace.formatToAlphanumeric())
    }

附:android 利用正則表達式 控制edittext只能輸入數字、英文、漢字

通過正則表達式來判斷。下面的例子只允許顯示字母、數字和漢字。

public static String stringFilter(String str)throws PatternSyntaxException{ ? ??
? ? ? // 只允許字母、數字和漢字 ? ? ?
? ? ? String ? regEx ?= ?"[^a-zA-Z0-9\u4E00-\u9FA5]"; ? ? ? ? ? ? ? ? ? ??
? ? ? Pattern ? p ? = ? Pattern.compile(regEx); ? ??
? ? ? Matcher ? m ? = ? p.matcher(str); ? ??
? ? ? return ? m.replaceAll("").trim(); ? ??
? }

//點擊事件調用上述方法

tv_other.setOnClickListener(new OnClickListener() {

? ?@Override
? ?public void onClick(View v) {
? ? // TODO Auto-generated method stub
? ? nicheng = ed_xiugainicheng.getText().toString();
? ? ? ? String str = stringFilter(nicheng.toString());
? ? ? ? ? ? if(!nicheng.equals(str)){
? ? ? ? ? ?Toast.makeText(WoXiuGaiNiChengActivity.this, "不能輸入非法字符!" , Toast.LENGTH_SHORT).show();
? ? }
}

總結

原文鏈接:https://blog.csdn.net/qq_20613731/article/details/123801486

欄目分類
最近更新