简体   繁体   English

Jackson YAML:使用标志映射正则表达式模式

[英]Jackson YAML: mapping a regex Pattern with flags

In Jackson, I can map a string in YAML:在 Jackson 中, 我可以在 YAML 中映射一个字符串:

regexField: "(\\d{2}):(\\d{2})"

to a Pattern field on a class:到类上的Pattern字段:

final class MappedFromYaml {
    private Pattern regexField;
    // ... accessors
}

Jackson's ObjectMapper will create a Pattern with default flags. Jackson 的ObjectMapper将创建一个带有默认标志的Pattern Is it possible to make it create it with specific flags set, such as Pattern.MULTILINE ?是否可以使用特定的标志集创建它,例如Pattern.MULTILINE Ideally I would like to be able to specify those flags in YAML, but failing that a solution that specifies the flags for a specific field in Java code would also be appreciated.理想情况下,我希望能够在 YAML 中指定这些标志,但如果未能在 Java 代码中为特定字段指定标志的解决方案也将不胜感激。

There are two ways.有两种方法。 The first is embedding flags directly into the regex :第一个是将标志直接嵌入到正则表达式中

regexField: "(\\d{2}):(\\d{2})(?m)"

Otherwise don't map directly to Pattern , but introduce a custom type like a PatternBuilder否则不要直接映射到Pattern ,而是引入一个像PatternBuilder这样的自定义类型

public class PatternBuilder {
  public String regex;
  public boolean multiline;
  public Pattern pattern() {
    int flags = 0;
    if (multiline) flags |= Pattern.MULTILINE;
    return Pattern.compile(regex, flags);
  }
}

that can be built from the YAML可以从 YAML 构建

pattern:
  regex: "(\\d{2}):(\\d{2})"
  multiline: true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM