Spring EL正規表現の例
Spring ELは単純なキーワード ”
matches
“を使って正規表現をサポートしています。これは本当にすごいです!たとえば、
@Value("#{'100' matches '\\d+' }") private boolean isDigit;
正規表現 ‘
\\ d
‘を使って ‘
100
‘が有効な数字かどうかをテストします。
AnnotationのSpring EL
次のSpring EL正規表現の例を参照してください.3つの演算子が混在するものもあり、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("[email protected]") 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="[email protected]"/> </bean>
</beans>
=== ソースコードをダウンロードする ダウンロードする - リンク://wp-content/uploads/2011/06/Spring3-EL-Regular-Expression-Example.zip[Spring3-EL- Regular-Expression-Example.zip](6 KB) === 参考文献 . link://正規表現/正規表現での電子メールアドレスの検証方法/[Email 正規表現の例]。リンク://spring3/spring-el-ternary-operator-if-then-else-example/[Spring EL三項演算子(if-then-else)の例] link://tag/regex/[regex]link://tag/spring-el/[spring el]link://tag/spring3/[spring3]