Sunday 22 March 2020

Regular Expression: Remove all non-numeric characters from string

Using Regular Expressions.
a.   str.replaceAll("[^\\d.]", "").replace(".", "")
b.   str.replaceAll("[^0-9.]", "").replace(".", "")
c.    str.replaceAll("\\D+", "")

\d: Matches a digit: [0-9]
\\D: Matches a non-digit: [^0-9]

You can even traverse every character of string and take only digits from string.

StringUtil.java
package com.smaple.app.utils;

public class StringUtil {
 public static String removeNonNumericChars_approach1(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  return str.replaceAll("[^\\d.]", "").replace(".", "");
 }

 public static String removeNonNumericChars_approach2(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  return str.replaceAll("[^0-9.]", "").replace(".", "");
 }

 public static String removeNonNumericChars_approach3(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  return str = str.replaceAll("\\D+", "");
 }

 public static String removeNonNumericChars_approach4(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  StringBuilder builder = new StringBuilder();

  for (int i = 0; i < str.length(); i++) {
   char currentChar = str.charAt(i);

   if (Character.isDigit(currentChar)) {
    builder.append(currentChar);
   }

  }

  return builder.toString();
 }

}

StringUtilTest.java

package com.sample.app.utils;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.smaple.app.utils.StringUtil;

public class StringUtilTest {

 @Test
 public void emptyString() {
  String str = "";

  assertEquals(StringUtil.removeNonNumericChars_approach1(str), "");
  assertEquals(StringUtil.removeNonNumericChars_approach2(str), "");
  assertEquals(StringUtil.removeNonNumericChars_approach3(str), "");
  assertEquals(StringUtil.removeNonNumericChars_approach4(str), "");
 }

 @Test
 public void nullString() {
  String str = null;

  assertEquals(StringUtil.removeNonNumericChars_approach1(str), null);
  assertEquals(StringUtil.removeNonNumericChars_approach2(str), null);
  assertEquals(StringUtil.removeNonNumericChars_approach3(str), null);
  assertEquals(StringUtil.removeNonNumericChars_approach4(str), null);
 }

 @Test
 public void randomString() {

  List<String> input = Arrays.asList("a123.3334xyz.178x", "12#$%&^9", ";~`{}][]123");
  List<String> result = Arrays.asList("1233334178", "129", "123");

  for (int i = 0; i < input.size(); i++) {
   assertEquals(StringUtil.removeNonNumericChars_approach1(input.get(i)), result.get(i));
   assertEquals(StringUtil.removeNonNumericChars_approach2(input.get(i)), result.get(i));
   assertEquals(StringUtil.removeNonNumericChars_approach3(input.get(i)), result.get(i));
   assertEquals(StringUtil.removeNonNumericChars_approach4(input.get(i)), result.get(i));
  }

 }
}



You may like

No comments:

Post a Comment