Showing posts with label regular expression. Show all posts
Showing posts with label regular expression. Show all posts

Wednesday, 7 April 2021

Bean Validation: @Pattern: Match to given regular expression

@Pattern annotation is applied on a CharSequence (string), it makes sure that given field matches to the regular expression.

 

Example

@Pattern(regexp = "[a-zA-Z ]*")

private String name;

 

Employee.java

package com.sample.app.model;

import java.util.Date;

import javax.validation.constraints.Pattern;

public class Employee {

	private int id;

	@Pattern(regexp = "[a-zA-Z ]*")
	private String name;

	public Date joinedDate;

	public Employee(int id, String name, Date joinedDate) {
		this.id = id;
		this.name = name;
		this.joinedDate = joinedDate;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getJoinedDate() {
		return joinedDate;
	}

	public void setJoinedDate(Date joinedDate) {
		this.joinedDate = joinedDate;
	}

}

 

Test.java

package com.sample.app;

import java.util.Calendar;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.sample.app.model.Employee;

public class Test {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Employee emp) {
		System.out.println("************************************");
		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {

		Employee emp1 = new Employee(1, "Rama Krishna", Calendar.getInstance().getTime());
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", Calendar.getInstance().getTime());
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
		
		Employee emp3 = new Employee(3, "Siva553", Calendar.getInstance().getTime());
		System.out.println("Validation errors on bean emp3");
		validateBean(emp3);
	}
}

 

Output

Validation errors on bean emp1
************************************
No validation errors....

Validation errors on bean emp2
************************************
No validation errors....

Validation errors on bean emp3
************************************
name,must match "[a-zA-Z ]*"

 

 

 

 

  

Previous                                                    Next                                                    Home

Thursday, 26 March 2020

Regular Expression: Split a string by the pipe symbol

Suppose you have a string with | characters in it. Since | is a regular expression character we need to escape it while splitting the string like below.

String[] tokens = str.split("\\|");

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  String str = "Hello|How|Are|You";
  
  String[] tokens = str.split("\\|");
  
  for(String token : tokens) {
   System.out.println(token);
  }

 }

}

Output
Hello
How
Are
You


Previous                                                    Next                                                    Home

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

Sunday, 15 March 2020

Regex: Lookahead and Lookbehind: Split a string by keeping delimiters

Using Lookahead and Lookbehind operators, we can split the string by keeping delimiters.

Following table summarizes lookahead and lookbehind operators.

Operator
Example
Description
Lookahead
(?=foo)
Asserts that what immediately follows the current position in the string is foo
Lookbehind
(?<=foo)
Asserts that what immediately precedes the current position in the string is foo

App.java
package com.sample.app;

import java.util.Arrays;

public class App {

 private static String[] splitByDelimiterUsingLookBehind(String str, String delimiter) {
  return str.split("(?<=" + delimiter + ")");
 }

 private static String[] splitByDelimiterUsingLookAhead(String str, String delimiter) {
  return str.split("(?=" + delimiter + ")");
 }

 private static void printArray(String[] str) {
  System.out.println(Arrays.toString(str));
 }

 public static void main(String args[]) throws InterruptedException {
  String[] result = splitByDelimiterUsingLookAhead("a#b#c#d", "#");
  printArray(result);

  result = splitByDelimiterUsingLookBehind("a#b#c#d", "#");
  printArray(result);
 }

}

Output
[a, #b, #c, #d]
[a#, b#, c#, d]



Previous                                                    Next                                                    Home

Saturday, 15 February 2020

Regular Expression : matches vs find

‘matches’ method return true if the entire sequence matches to given regular expression. Whereas ‘find’ method scans the input sequence looking for the next subsequence that matches the pattern.

matches method example
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);
                
                System.out.println("Is pattern matched : " + matcher.matches());
                System.out.println();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
a*b
Enter the string
abbb
Is pattern matched : false

Enter the string
aaab
Is pattern matched : true

Enter the string
xb
Is pattern matched : false

find method example
RegExHarness.java
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                while(matcher.find()){
                    System.out.print("I found the text " + matcher.group());
                    System.out.print(" starting at index " + matcher.start());
                    System.out.println(" Ending at index " + matcher.end());
                }
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
is
Enter the string
this is easy task... is it?
I found the text is starting at index 2 Ending at index 4
I found the text is starting at index 5 Ending at index 7
I found the text is starting at index 21 Ending at index 23



Previous                                                    Next                                                    Home