本文介绍了杰克逊YAML:映射带有标志的正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在杰克逊中,我可以映射 YAML中的字符串:

In Jackson, I can map a string in YAML:

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

转到类的 Pattern 字段:

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

Jackson的 ObjectMapper 将创建带有默认标志的 Pattern .是否可以通过设置特定的标志(例如 Pattern.MULTILINE )来创建它?理想情况下,我希望能够在YAML中指定这些标志,但是如果未能通过解决方案为Java代码中的特定字段指定标志的解决方案,那将不胜感激.

Jackson's ObjectMapper will create a Pattern with default flags. Is it possible to make it create it with specific flags set, such as 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.

推荐答案

有两种方法.首先是将标志直接嵌入到正则表达式中:

There are two ways. The first is embedding flags directly into the regex:

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

否则,不要直接映射到 Pattern ,而是引入自定义类型,例如 PatternBuilder

Otherwise don't map directly to Pattern, but introduce a custom type like a 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);
  }
}

可以从YAML构建的

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

这篇关于杰克逊YAML:映射带有标志的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 22:55