com.google.re2j.PatternSyntaxException Java Examples

The following examples show how to use com.google.re2j.PatternSyntaxException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VerifyMatch.java    From copybara with Apache License 2.0 5 votes vote down vote up
public static VerifyMatch create(Location location, String regEx, Glob paths,
    boolean verifyNoMatch, boolean alsoOnReversal, LocalParallelizer parallelizer)
    throws EvalException {
  Pattern parsed;
  try {
    parsed = Pattern.compile(regEx, Pattern.MULTILINE);
  } catch (PatternSyntaxException e) {
    throw new EvalException(location, String.format("Regex '%s' is invalid.", regEx), e);
  }
  return new VerifyMatch(parsed, verifyNoMatch, alsoOnReversal, paths, parallelizer, location);
}
 
Example #2
Source File: Replace.java    From copybara with Apache License 2.0 5 votes vote down vote up
public static Replace create(Location location, String before, String after,
    Map<String, String> regexGroups, Glob paths, boolean firstOnly, boolean multiline,
    boolean repeatedGroups, List<String> patternsToIgnore,
    WorkflowOptions workflowOptions)
    throws EvalException {
  Map<String, Pattern> parsedGroups = parsePatterns(regexGroups);

  RegexTemplateTokens beforeTokens =
      new RegexTemplateTokens(location, before, parsedGroups, repeatedGroups);
  RegexTemplateTokens afterTokens =
      new RegexTemplateTokens(location, after, parsedGroups, repeatedGroups);

  beforeTokens.validateUnused();

  List<Pattern> parsedIgnorePatterns = new ArrayList<>();
  for (String toIgnore : patternsToIgnore) {
    try {
      parsedIgnorePatterns.add(Pattern.compile(toIgnore));
    } catch (PatternSyntaxException e) {
      throw Starlark.errorf("'patterns_to_ignore' includes invalid regex: %s", toIgnore);
    }
  }

  // Don't validate non-used interpolations in after since they are only relevant for reversable
  // transformations. And those are eagerly validated during config loading, because
  // when asking for the reverse 'after' is used as 'before', and it gets validated
  // with the check above.

  return new Replace(
      beforeTokens, afterTokens, parsedGroups, firstOnly, multiline, repeatedGroups, paths,
      parsedIgnorePatterns, workflowOptions, location);
}
 
Example #3
Source File: Replace.java    From copybara with Apache License 2.0 5 votes vote down vote up
public static Map<String, Pattern> parsePatterns(Map<String, String> regexGroups)
    throws EvalException {
  Map<String, Pattern> parsedGroups = new HashMap<>();
  for (Entry<String, String> group : regexGroups.entrySet()) {
    try {
      parsedGroups.put(group.getKey(), Pattern.compile(group.getValue()));
    } catch (PatternSyntaxException e) {
      throw Starlark.errorf(
          "'regex_groups' includes invalid regex for key %s: %s",
          group.getKey(), group.getValue());
    }
  }
  return parsedGroups;
}
 
Example #4
Source File: MetadataModule.java    From copybara with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
@StarlarkMethod(
    name = "verify_match",
    doc =
        "Verifies that a RegEx matches (or not matches) the change message. Does not"
            + " transform anything, but will stop the workflow if it fails.",
    parameters = {
      @Param(
          name = "regex",
          type = String.class,
          named = true,
          doc =
              "The regex pattern to verify. The re2j pattern will be applied in multiline"
                  + " mode, i.e. '^' refers to the beginning of a file and '$' to its end."),
      @Param(
          name = "verify_no_match",
          type = Boolean.class,
          named = true,
          doc = "If true, the transformation will verify that the RegEx does not match.",
          defaultValue = "False"),
    },
    useStarlarkThread = true)
@Example(
    title = "Check that a text is present in the change description",
    before = "Check that the change message contains a text enclosed in <public></public>:",
    code = "metadata.verify_match(\"<public>(.|\\n)*</public>\")")
public Transformation verifyMatch(String regex, Boolean verifyNoMatch, StarlarkThread thread)
    throws EvalException {
  Pattern pattern;
  try {
    pattern = Pattern.compile(regex, Pattern.MULTILINE);
  } catch (PatternSyntaxException e) {
    throw Starlark.errorf("Invalid regex expression: %s", e.getMessage());
  }
  return new MetadataVerifyMatch(pattern, verifyNoMatch, thread.getCallerLocation());
}
 
Example #5
Source File: AutoCompleteUtils.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** Returns the Pattern if {@code candidateRegex} is a valid regex, and null otherwise */
@Nullable
private static Pattern safeGetPattern(String candidateRegex) {
  try {
    return Pattern.compile(candidateRegex);
  } catch (PatternSyntaxException e) {
    return null;
  }
}
 
Example #6
Source File: RegexReplaceFilter.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  if (args.length < 2) {
    throw new TemplateSyntaxException(
      interpreter,
      getName(),
      "requires 2 arguments (regex string, replacement string)"
    );
  }

  if (var == null) {
    return null;
  }

  if (var instanceof String) {
    String s = (String) var;
    String toReplace = args[0];
    String replaceWith = args[1];

    try {
      Pattern p = Pattern.compile(toReplace);
      Matcher matcher = p.matcher(s);

      return matcher.replaceAll(replaceWith);
    } catch (PatternSyntaxException e) {
      throw new InvalidArgumentException(
        interpreter,
        this,
        InvalidReason.REGEX,
        0,
        toReplace
      );
    }
  } else {
    throw new InvalidInputException(interpreter, this, InvalidReason.STRING);
  }
}
 
Example #7
Source File: EnvoyProtoData.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static StructOrError<PathMatcher> convertEnvoyProtoPathMatcher(
    io.envoyproxy.envoy.api.v2.route.RouteMatch proto) {
  String path = null;
  String prefix = null;
  Pattern safeRegEx = null;
  switch (proto.getPathSpecifierCase()) {
    case PREFIX:
      prefix = proto.getPrefix();
      break;
    case PATH:
      path = proto.getPath();
      break;
    case REGEX:
      return StructOrError.fromError("Unsupported path match type: regex");
    case SAFE_REGEX:
      String rawPattern = proto.getSafeRegex().getRegex();
      try {
        safeRegEx = Pattern.compile(rawPattern);
      } catch (PatternSyntaxException e) {
        return StructOrError.fromError("Malformed safe regex pattern: " + e.getMessage());
      }
      break;
    case PATHSPECIFIER_NOT_SET:
    default:
      return StructOrError.fromError("Unknown path match type");
  }
  return StructOrError.fromStruct(new PathMatcher(path, prefix, safeRegEx));
}
 
Example #8
Source File: EnvoyProtoData.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
@SuppressWarnings("deprecation")
static StructOrError<HeaderMatcher> convertEnvoyProtoHeaderMatcher(
    io.envoyproxy.envoy.api.v2.route.HeaderMatcher proto) {
  String exactMatch = null;
  Pattern safeRegExMatch = null;
  HeaderMatcher.Range rangeMatch = null;
  Boolean presentMatch = null;
  String prefixMatch = null;
  String suffixMatch = null;

  switch (proto.getHeaderMatchSpecifierCase()) {
    case EXACT_MATCH:
      exactMatch = proto.getExactMatch();
      break;
    case REGEX_MATCH:
      return StructOrError.fromError(
          "HeaderMatcher [" + proto.getName() + "] has unsupported match type: regex");
    case SAFE_REGEX_MATCH:
      String rawPattern = proto.getSafeRegexMatch().getRegex();
      try {
        safeRegExMatch = Pattern.compile(rawPattern);
      } catch (PatternSyntaxException e) {
        return StructOrError.fromError(
            "HeaderMatcher [" + proto.getName() + "] contains malformed safe regex pattern: "
                + e.getMessage());
      }
      break;
    case RANGE_MATCH:
      rangeMatch =
          new HeaderMatcher.Range(
              proto.getRangeMatch().getStart(), proto.getRangeMatch().getEnd());
      break;
    case PRESENT_MATCH:
      presentMatch = proto.getPresentMatch();
      break;
    case PREFIX_MATCH:
      prefixMatch = proto.getPrefixMatch();
      break;
    case SUFFIX_MATCH:
      suffixMatch = proto.getSuffixMatch();
      break;
    case HEADERMATCHSPECIFIER_NOT_SET:
    default:
      return StructOrError.fromError("Unknown header matcher type");
  }
  return StructOrError.fromStruct(
      new HeaderMatcher(
          proto.getName(), exactMatch, safeRegExMatch, rangeMatch, presentMatch,
          prefixMatch, suffixMatch, proto.getInvertMatch()));
}