Spring spel regex tutorial

Spring SpEL Regex:

Spring SpEL provides the facility to support regular expressions using keyword “matches“.

Syntax:

#{'value' matches 'regex' }

Example:

RegexTest.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("regexTestBean")
public class RegexTest {
    // Check if this is a digit or not?
	@Value("#{'250' matches '\\d+' }")
	private boolean validDigit;

	public boolean isValidDigit() {
		return validDigit;
	}

	public void setValidDigit(boolean validDigit) {
		this.validDigit = validDigit;
	}
	
}

applicationContext.xml



 


Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring SPEL Regex example.
 * @author W3schools360
 */
public class Test {
 public static void main(String args[]){	
  //Get application context object.
  ApplicationContext context = 
	new ClassPathXmlApplicationContext("applicationContext.xml");

  //Get regexTestBean.
  RegexTest regexTest = (RegexTest) context.getBean("regexTestBean");

  //Test data.
  System.out.println("Is valid: "+regexTest.isValidDigit()); 
 }
}

Output:

Is valid: true

 
Download this example.