View Javadoc
1   /*
2    * Copyright 2018 Andrew Rucker Jones.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.opencsv.bean;
17  
18  import com.opencsv.bean.util.OpencsvUtils;
19  
20  import java.util.Locale;
21  import java.util.regex.Matcher;
22  import java.util.regex.Pattern;
23  
24  /**
25   * Maps any header name matching a regular expression to a {@link BeanField}.
26   *
27   * @param <T> The type of the bean being converted
28   * @author Andrew Rucker Jones
29   * @since 4.2
30   */
31  public class RegexToBeanField<T> extends AbstractFieldMapEntry<String, String, T> {
32  
33      /** The compiled regular expression used to match header names. */
34      private final Pattern regex;
35  
36      /**
37       * Initializes this mapping with the regular expression used to map header
38       * names and the {@link BeanField} they should be mapped to.
39       * 
40       * @param pattern A valid regular expression against which potential header
41       *   names are matched
42       * @param field The {@link BeanField} this mapping maps to
43       * @param errorLocale The locale for error messages
44       */
45      public RegexToBeanField(final String pattern, final BeanField<T, String> field, final Locale errorLocale) {
46          super(field, errorLocale);
47          regex = OpencsvUtils.compilePattern(pattern, Pattern.CASE_INSENSITIVE, BeanFieldJoin.class, this.errorLocale);
48      }
49      
50      @Override
51      public boolean contains(String key) {
52          final Matcher m = regex.matcher(key);
53          return m.matches();
54      }
55      
56      @Override
57      public String getInitializer() {
58          return regex.pattern();
59      }
60  }