001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.beans.propertyeditors; 018 019import java.beans.PropertyEditorSupport; 020import java.util.regex.Pattern; 021 022import org.springframework.lang.Nullable; 023 024/** 025 * Editor for {@code java.util.regex.Pattern}, to directly populate a Pattern property. 026 * Expects the same syntax as Pattern's {@code compile} method. 027 * 028 * @author Juergen Hoeller 029 * @since 2.0.1 030 * @see java.util.regex.Pattern 031 * @see java.util.regex.Pattern#compile(String) 032 */ 033public class PatternEditor extends PropertyEditorSupport { 034 035 private final int flags; 036 037 038 /** 039 * Create a new PatternEditor with default settings. 040 */ 041 public PatternEditor() { 042 this.flags = 0; 043 } 044 045 /** 046 * Create a new PatternEditor with the given settings. 047 * @param flags the {@code java.util.regex.Pattern} flags to apply 048 * @see java.util.regex.Pattern#compile(String, int) 049 * @see java.util.regex.Pattern#CASE_INSENSITIVE 050 * @see java.util.regex.Pattern#MULTILINE 051 * @see java.util.regex.Pattern#DOTALL 052 * @see java.util.regex.Pattern#UNICODE_CASE 053 * @see java.util.regex.Pattern#CANON_EQ 054 */ 055 public PatternEditor(int flags) { 056 this.flags = flags; 057 } 058 059 060 @Override 061 public void setAsText(@Nullable String text) { 062 setValue(text != null ? Pattern.compile(text, this.flags) : null); 063 } 064 065 @Override 066 public String getAsText() { 067 Pattern value = (Pattern) getValue(); 068 return (value != null ? value.pattern() : ""); 069 } 070 071}