SoFunction
Updated on 2025-03-02

How to use regular expressions to preserve only alphanumeric

Preface

Regular expressions are a logical formula for string operations, which is to use some specific characters defined in advance and combinations of these specific characters to form a "rule string". This "rule string" is used to express a filtering logic for strings.

#1. Characters matching letters (upper case/lower case) and numbers

Regular expression:[^a-zA-Z0-9]

#2. Use regular expressions to process the given string, keeping only letters and numbers:

We need to replace non-letters and numbers with empty replacement, that is, we need to match non-letters and numbers.

The regular expression is:[^a-zA-Z0-9]

/**
  * Remove special characters and display only alphanumeric characters:
  * No dash, no hash, no crash or slash, no spaces, etc.
  *
  * @return The string only has alphanumeric characters
  */
fun (): String = ("[^a-zA-Z0-9]*".toRegex(), "")

#3. Add unit tests:

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

Attachment: Android uses regular expressions to control edittext to only enter numbers, English, and Chinese characters.

Judge by regular expressions. The following examples allow only letters, numbers and Chinese characters to be displayed.

public static String stringFilter(String str)throws PatternSyntaxException{     
      // Only letters, numbers and Chinese characters are allowed      String   regEx  =  "[^a-zA-Z0-9\u4E00-\u9FA5]";                     
      Pattern   p   =   (regEx);     
      Matcher   m   =   (str);     
      return   ("").trim();     
  }

//Click the event to call the above method
tv_other.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    nicheng = ed_xiugainicheng.getText().toString();
        String str = stringFilter(());
            if(!(str)){
           (, "Illegal characters cannot be entered!" , Toast.LENGTH_SHORT).show();
    }
}

Summarize

This is the article about how Android uses regular expressions to retain only alphanumeric characters. For more related content related to Android regular retaining alphanumeric characters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!