Java regex program to add space between a number and word in Java.



You can form matched groups in the regular expression by separating the expressions with parenthesis. In following regular expression the first group matches digits and the second group matches the English alphabet −

(\d)([A-Za-z])

In short, it matches the part in the input string where a digit followed by an alphabet.

Since the expression $1 indicates Group1 and $2 indicates Group2, if you replace The above Java regular expression with $1 $2, using the replace() method (of the String class) a space will be added between number and a word in the given input string when a number is followed by a word.

Example

 Live Demo

import java.util.Scanner;
public class SampleTest {
   public static void main( String args[] ) {
      String regex = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      //String result = input.replaceAll(regex, " ");
      String result = input.replaceAll( "(\d)([A-Za-z])", "$1 $2" );
      System.out.println(result);
   }
}

Output

Enter input text:
21This 23is 56sample 99text
21 This 23 is 56 sample 99 text

Similarly, you can add space between numbers and alphabets in the given text irrespective of the order you need to replace the following expression with a space −

(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])

Example

 Live Demo

import java.util.Scanner;
public class SampleTest {
   public static void main( String args[] ) {
      String regex = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      //String result = input.replaceAll(regex, " ");
      String result = input.replaceAll( regex, " " );
      System.out.println(result);
   }
}

Output

Enter input text:
21This23is56sample99text
21 This 23 is 56 sample 99 text

Advertisements