Spring EL正则表达式示例

Spring EL使用简单的关键字“ matches ”支持正则表达式,这真是太棒了! 举些例子,

@Value("#{'100' matches '\\d+' }")
	private boolean isDigit;

它通过正则表达式' \\ d + '测试' 100 '是否为有效数字。

注释中的Spring EL

请参阅以下Spring EL正则表达式示例,其中一些与三元运算符混合使用,这使Spring EL变得非常灵活和强大。

下面的示例应该是不言自明的。

package com.mkyong.core;

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

@Component("customerBean")
public class Customer {

	// email regular expression
	String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)" +
			"*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	// if this is a digit?
	@Value("#{'100' matches '\\d+' }")
	private boolean validDigit;

	// if this is a digit + ternary operator
	@Value("#{ ('100' matches '\\d+') == true ? " +
			"'yes this is digit' : 'No this is not a digit'  }")
	private String msg;

	// if this emailBean.emailAddress contains a valid email address?
	@Value("#{emailBean.emailAddress matches customerBean.emailRegEx}")
	private boolean validEmail;

	//getter and setter methods, and constructor	
}
package com.mkyong.core;

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

@Component("emailBean")
public class Email {

	@Value("nospam@abc.com")
	String emailAddress;

	//...
}

输出量

Customer [isDigit=true, msg=yes this is digit, isValidEmail=true]

XML中的Spring EL

请参见bean定义XML文件中的等效版本。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="customerBean" class="com.mkyong.core.Customer">
	  <property name="validDigit" value="#{'100' matches '\d+' }" />
	  <property name="msg"
		value="#{ ('100' matches '\d+') == true ? 'yes this is digit' : 'No this is not a digit'  }" />
	  <property name="validEmail"
		value="#{emailBean.emailAddress matches '^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$' }" />
	</bean>

	<bean id="emailBean" class="com.mkyong.core.Email">
	  <property name="emailAddress" value="nospam@abc.com" />
	</bean>

</beans>

下载源代码

下载它– Spring3-EL-Regular-Expression-Example.zip (6 KB)

参考文献

  1. 电子邮件正则表达式示例
  2. Spring EL三元运算符(if-then-else)示例

翻译自: https://mkyong.com/spring3/spring-el-regular-expression-example/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值