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

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:component-scan base-package="com.w3schools.business" />
 
</beans>

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
/**
 * Spring SPEL Regex example.
 * @author w3schools
 */
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.