Spring ELの正規表現の例
Spring ELは、単純なキーワード「matches」を使用した正規表現をサポートしています。これは本当に素晴らしいです! たとえば、
@Value("#{'100' matches '\\d+' }") private boolean isDigit;
正規表現 ‘\d+‘を使用して、 ‘100‘が有効な数字であるかどうかをテストします。
注釈のSpring EL
次のSpring EL正規表現の例を参照してください。一部には三項演算子が混在しているため、Spring ELは非常に柔軟で強力です。
以下の例は一目瞭然です。
package com.example.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.example.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ファイルで同等のバージョンを参照してください。
ソースコードをダウンロード
ダウンロード–Spring3-EL-Regular-Expression-Example.zip(6 KB)