下面列出了怎么用java.util.regex.PatternSyntaxException的API类实例代码及写法,或者点击链接到github查看源代码。
public void downloadSkipRegexFieldDidChange(final NSNotification sender) {
String value = this.downloadSkipRegexField.string().trim();
if(StringUtils.EMPTY.equals(value)) {
preferences.setProperty("queue.download.skip.enable", false);
preferences.setProperty("queue.download.skip.regex", value);
this.downloadSkipButton.setState(NSCell.NSOffState);
}
try {
Pattern compiled = Pattern.compile(value);
preferences.setProperty("queue.download.skip.regex",
compiled.pattern());
this.mark(this.downloadSkipRegexField.textStorage(), null);
}
catch(PatternSyntaxException e) {
this.mark(this.downloadSkipRegexField.textStorage(), e);
}
}
@Test
public void testPathMatchers_glob() {
assertThatPath("bar").matches("glob:bar");
assertThatPath("bar").matches("glob:*");
assertThatPath("C:\\foo").doesNotMatch("glob:*");
assertThatPath("C:\\foo\\bar").doesNotMatch("glob:*");
assertThatPath("C:\\foo\\bar").matches("glob:**");
assertThatPath("C:\\foo\\bar").matches("glob:C:\\\\**");
assertThatPath("foo\\bar").doesNotMatch("glob:C:\\\\**");
assertThatPath("C:\\foo\\bar\\baz\\stuff").matches("glob:C:\\\\foo\\\\**");
assertThatPath("C:\\foo\\bar\\baz\\stuff").matches("glob:C:\\\\**\\\\stuff");
assertThatPath("C:\\foo").matches("glob:C:\\\\[a-z]*");
assertThatPath("C:\\Foo").matches("glob:C:\\\\[a-z]*");
assertThatPath("C:\\foo").matches("glob:C:\\\\[A-Z]*");
assertThatPath("C:\\Foo").matches("glob:C:\\\\[A-Z]*");
assertThatPath("C:\\foo\\bar\\baz\\Stuff.java").matches("glob:**\\\\*.java");
assertThatPath("C:\\foo\\bar\\baz\\Stuff.java").matches("glob:**\\\\*.{java,class}");
assertThatPath("C:\\foo\\bar\\baz\\Stuff.class").matches("glob:**\\\\*.{java,class}");
assertThatPath("C:\\foo\\bar\\baz\\Stuff.java").matches("glob:**\\\\*.*");
try {
fs.getPathMatcher("glob:**\\*.{java,class");
fail();
} catch (PatternSyntaxException expected) {
}
}
@Override
public void performApply(IProgressMonitor monitor) throws CoreException {
// normally should be handled by LanguageSettingsProviderTab
final String text = pattern.getText();
try {
Pattern.compile(text);
} catch (PatternSyntaxException ex) {
// BUG in CDT: core exceptions thrown here are not visible to users. CDT-WTF
// IStatus status = new Status(IStatus.ERROR, Plugin.PLUGIN_ID,
// IStatus.OK,
// "invalid suffix pattern in CMAKE_EXPORT_COMPILE_COMMANDS Parser", ex);
// throw new CoreException(status);
throw new PatternSyntaxException(
"Invalid suffix pattern in CMAKE_EXPORT_COMPILE_COMMANDS Parser:\n" + ex.getDescription(), ex.getPattern(),
ex.getIndex());
}
}
private Attribute[] getAttributesArrayFromRegex(Attributes attributes, String regex) throws OperatorException {
Pattern pattern = null;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, regex, e.getMessage());
}
List<Attribute> attributeList = new LinkedList<>();
Iterator<Attribute> i = attributes.allAttributes();
while (i.hasNext()) {
Attribute attribute = i.next();
Matcher matcher = pattern.matcher(attribute.getName());
if (matcher.matches()) {
attributeList.add(attribute);
}
}
Attribute[] attributesArray = new Attribute[attributeList.size()];
attributesArray = attributeList.toArray(attributesArray);
return attributesArray;
}
private void loadConf() {
Properties cfg = ConfigLoader.loadPluginConfig("dupecheck.conf");
String exempt = cfg.getProperty("exempt");
String type = cfg.getProperty("type");
if (exempt != null) {
_exempt = null;
try {
_exempt = Pattern.compile(exempt.trim());
logger.debug("Exempt pattern parsed and compiled succesffull [{}]", _exempt.toString());
} catch(PatternSyntaxException pse) {
logger.error("Provided exempt pattern is incorrectly formatted", pse);
}
}
if (type != null) {
_type = Integer.parseInt(type.trim());
if (_type < 0 || _type > 3) {
logger.error("Incorrect type {} found, ignoring and disabling dupechecking", type);
_type = 0;
}
}
logger.info("Dupe checking type has been set to {}", _type);
}
public final Map<String, Set<String>> excludeConfiguredImports(
final Map<String, Set<String>> importsVsMethods, final Set<String> excludeImports) {
Map<String, Set<String>> finalImportsVsMethods = new HashMap<>();
finalImportsVsMethods.putAll(importsVsMethods);
Set<Map.Entry<String, Set<String>>> entrySet = importsVsMethods.entrySet();
for (String importStatement : excludeImports) {
Pattern pattern = Pattern.compile(importStatement);
for (Map.Entry<String, Set<String>> entry : entrySet) {
try {
String entryImport = entry.getKey();
Matcher matcher = pattern.matcher(entryImport);
if (matcher.find()) {
finalImportsVsMethods.remove(entryImport);
}
} catch (PatternSyntaxException e) {
KBNotification.getInstance().error(e);
e.printStackTrace();
}
}
}
return finalImportsVsMethods;
}
/**
* Converts the given list of Strings to a list of Pattern objects
*
* @param regexps
* A list of regex pattern strings
*
* @exception IllegalArgumentException
* if one of the patterns has invalid regular expression
* syntax
*/
private List<Pattern> getRegExPatterns(List<String> regexps) {
ArrayList<Pattern> patterns = new ArrayList<>();
for (String regexp : regexps) {
String regex = StringUtils.trimToNull(regexp);
if (regex != null) {
// if :empty: is in any of the then return an empty list
if (StringUtils.equals(":empty:", regex)) return new ArrayList<>();
try {
patterns.add(Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Illegal Regular Expression Syntax: [" + regex + "] - " + e.getMessage());
}
}
}
return patterns;
}
/**
* Creates a new builder instance.
*
* @param platform The plaftform this builder belongs to
*/
public Oracle8Builder(Platform platform)
{
super(platform);
addEscapedCharSequence("'", "''");
try
{
_isoDatePattern = Pattern.compile("\\d{4}\\-\\d{2}\\-\\d{2}");
_isoTimePattern = Pattern.compile("\\d{2}:\\d{2}:\\d{2}");
_isoTimestampPattern = Pattern.compile("\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}[\\.\\d{1,8}]?");
}
catch (PatternSyntaxException ex)
{
throw new DdlUtilsException(ex);
}
}
/**
* Parse a literal value and put into the pattern cache if it does not exist.
*
* @param node
*/
public void parseAndPutPattern(JexlNode node) {
// Catch the situation where a user might enter FIELD1 !~ VALUE1
Object literalValue = JexlASTHelper.getLiteralValue(node);
if (literalValue != null && String.class.equals(literalValue.getClass())) {
String literalString = (String) literalValue;
try {
if (patternCache.containsKey(literalString)) {
return;
}
patternCache.put(literalString, Pattern.compile(literalString));
} catch (PatternSyntaxException e) {
String builtNode = JexlStringBuildingVisitor.buildQueryWithoutParse(node);
String errMsg = "Invalid pattern found in filter function '" + builtNode + "'";
throw new PatternSyntaxException(errMsg, e.getPattern(), e.getIndex());
}
}
}
/**
* Sets proper color of file pattern.
*/
private void updateFileNamePatternColor() {
boolean wasInvalid = patternValid;
String pattern = getFileNamePattern();
if (pattern == null || pattern.isEmpty()) {
patternValid = true;
} else {
try {
Pattern p = RegexpUtil.makeFileNamePattern(
SearchScopeOptions.create(getFileNamePattern(), regexp));
if (p == null) {
patternValid = false;
} else {
patternValid = true;
}
} catch (PatternSyntaxException e) {
patternValid = false;
}
}
if (patternValid != wasInvalid && !isAllFilesInfoDisplayed()) {
fileNamePatternEditor.setForeground(
patternValid ? defaultColor : UiUtils.getErrorTextColor());
}
}
private char parseEscapedUnicodeCharacter() {
consumeSymbol();
StringBuilder hexNumberStr = new StringBuilder();
/* Read next four symbols as hex number */
hexNumberStr.append(currentSymbol);
for (int i = 0; i < 4; i++) {
consumeSymbol();
hexNumberStr.append(currentSymbol);
}
try {
int hexNumber = Integer.parseInt(hexNumberStr.toString(), 16);
if (hexNumber >= MAX_16UNICODE) {
throw new PatternSyntaxException("Hexadecimal codepoint is too big", transitionLabelString, index);
}
return ((char) hexNumber);
} catch (NumberFormatException nfe) {
throw new PatternSyntaxException("Illegal hexadecimal escape sequence", transitionLabelString, index);
}
}
public RegexSelector(String regexStr, int group) {
if (StringUtils.isBlank(regexStr)) {
throw new IllegalArgumentException("regex must not be empty");
}
// Check bracket for regex group. Add default group 1 if there is no group.
// Only check if there exists the valid left parenthesis, leave regexp validation for Pattern.
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:")) {
regexStr = "(" + regexStr + ")";
}
this.regexStr = regexStr;
try {
regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("invalid regex", e);
}
this.group = group;
}
List<Pattern> getAsPatternList(final String[] src)
{
final List<Pattern> target = new ArrayList<Pattern>();
if (src != null) {
for (final String s : src) {
try {
final Pattern pattern = Pattern.compile(s);
target.add(pattern);
} catch (final PatternSyntaxException e) {
getLog().warn("The regex " + s + " is invalid: " + e.getLocalizedMessage());
}
}
}
return target;
}
private void filterVersionPattern(List<ArtifactVersion> availableVersions, PluginParameters pluginParameters) throws MojoFailureException {
if (pluginParameters.getParameterParam() != null && pluginParameters.getParameterParam().getOldVersionPattern() != null) {
String versionPattern = pluginParameters.getParameterParam().getOldVersionPattern();
Pattern pattern;
try {
pattern = Pattern.compile(versionPattern);
} catch (PatternSyntaxException e) {
throw new MojoFailureException("Could not compile provided versionPattern '" + versionPattern + "' as regular expression: " + e.getMessage(), e);
}
for (Iterator<ArtifactVersion> versionIterator = availableVersions.iterator(); versionIterator.hasNext(); ) {
ArtifactVersion version = versionIterator.next();
Matcher matcher = pattern.matcher(version.toString());
if (!matcher.matches()) {
versionIterator.remove();
if (getLog().isDebugEnabled()) {
getLog().debug("Filtering version '" + version.toString() + "' because it does not match configured versionPattern '" + versionPattern + "'.");
}
}
}
} else {
getLog().debug("Parameter <oldVersionPattern> not configured, i.e. no version filtered.");
}
}
/**
* regexPatternMatch
*
* @param regex
* @param word
* @return
*/
private static boolean regexPatternMatch(String regex, String word, boolean caseSensitive)
{
Pattern pattern = PATTERNS.get(regex);
if (pattern == null)
{
try
{
// compile the pattern
pattern = (caseSensitive) ? Pattern.compile(regex) : Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
// cache for later
PATTERNS.put(regex, pattern);
}
catch (PatternSyntaxException e)
{
}
}
return (pattern != null) ? pattern.matcher(word).find() : false;
}
@Override
public List<BusinessObjectProperty> findBusinessObjectProperties(String namespaceCode, String componentLabel, String propertyLabel) {
List<BusinessObjectComponent> businessObjectComponents = findBusinessObjectComponents(namespaceCode, componentLabel);
Pattern propertyLabelRegex = null;
if (StringUtils.isNotBlank(propertyLabel)) {
String patternStr = propertyLabel.replace("*", ".*").toUpperCase();
try {
propertyLabelRegex = Pattern.compile(patternStr);
}
catch (PatternSyntaxException ex) {
LOG.error("KfsBusinessObjectMetaDataServiceImpl unable to parse propertyLabel pattern, ignoring.", ex);
}
}
List<BusinessObjectProperty> matchingBusinessObjectProperties = new ArrayList<BusinessObjectProperty>();
for (BusinessObjectComponent businessObjectComponent : businessObjectComponents) {
for (AttributeDefinition attributeDefinition : dataDictionaryService.getDataDictionary().getBusinessObjectEntry(businessObjectComponent.getComponentClass().toString()).getAttributes()) {
if (!attributeDefinition.getName().endsWith(KFSPropertyConstants.VERSION_NUMBER) && !attributeDefinition.getName().endsWith(KFSPropertyConstants.OBJECT_ID) && ((propertyLabelRegex == null) || propertyLabelRegex.matcher(attributeDefinition.getLabel().toUpperCase()).matches())) {
matchingBusinessObjectProperties.add(new BusinessObjectProperty(businessObjectComponent, attributeDefinition));
}
}
}
return matchingBusinessObjectProperties;
}
private Collection<Pattern> getSubjectContraints(Message msg) throws PatternSyntaxException {
String certConstraints =
(String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SUBJECT_CERT_CONSTRAINTS, msg);
// Check the message property first. If this is not null then use it. Otherwise pick up
// the constraints set as a property
if (certConstraints != null) {
String[] certConstraintsList = certConstraints.split(",");
if (certConstraintsList != null) {
subjectDNPatterns.clear();
for (String certConstraint : certConstraintsList) {
subjectDNPatterns.add(Pattern.compile(certConstraint.trim()));
}
}
}
return subjectDNPatterns;
}
/**
* Returns a {@link Pattern} object corresponding to the substring pattern
* specified in the criteria.
*
* @return {@code Pattern} object, or {@code null} if no pattern has been
* specified
*/
Pattern getTextPattern() {
if (!textPatternValid || !textPatternSpecified) {
return null;
}
if (textPattern != null) {
return textPattern;
}
try {
return TextRegexpUtil.makeTextPattern(searchPattern);
} catch (PatternSyntaxException e) {
textPatternValid = false;
return null;
}
}
private static Condition<CharSequence> getFileTypeMaskPattern(@Nullable String mask) {
try {
return FindInProjectUtil.createFileMaskCondition(mask);
} catch (PatternSyntaxException e) {
LOG.info("Error while processing file mask: ", e);
return Conditions.alwaysTrue();
}
}
public RegexFilter(Collection<String> patterns) throws PatternSyntaxException {
Objects.requireNonNull(patterns);
if (patterns.isEmpty()) {
allMatch = true;
return;
}
patterns.forEach(p -> {
Pattern pattern = Pattern.compile(p);
compiledPatterns.add(pattern);
});
if (patterns.isEmpty()) {
allMatch = true;
}
}
/**
* Construct a Regular expression from the given {@code pattern} and {@code flags} strings.
*
* @param pattern RegExp pattern string
* @param flags RegExp flag string
* @throws ParserException if flags is invalid or pattern string has syntax error.
*/
public JoniRegExp(final String pattern, final String flags) throws ParserException {
super(pattern, flags);
int option = Option.SINGLELINE;
if (this.isIgnoreCase()) {
option |= Option.IGNORECASE;
}
if (this.isMultiline()) {
option &= ~Option.SINGLELINE;
option |= Option.NEGATE_SINGLELINE;
}
try {
RegExpScanner parsed;
try {
parsed = RegExpScanner.scan(pattern);
} catch (final PatternSyntaxException e) {
// refine the exception with a better syntax error, if this
// passes, just rethrow what we have
Pattern.compile(pattern, 0);
throw e;
}
if (parsed != null) {
final char[] javaPattern = parsed.getJavaPattern().toCharArray();
this.regex = new Regex(javaPattern, 0, javaPattern.length, option, Syntax.JAVASCRIPT);
this.groupsInNegativeLookahead = parsed.getGroupsInNegativeLookahead();
}
} catch (final PatternSyntaxException | JOniException e2) {
throwParserException("syntax", e2.getMessage());
} catch (StackOverflowError e3) {
throw new RuntimeException(e3);
}
}
@Override
public void validateParameters() {
try {
Pattern.compile(regularExpression);
} catch (PatternSyntaxException exception) {
throw new IllegalStateException(paramErrorMessage(), exception);
}
}
protected void compile(String pattern) throws PatternSyntaxException {
String escaped = StringUtils.escapeRegexp(pattern);
String regex = escaped.replace("_", ".").replace("%", ".*");
int flags = Pattern.DOTALL;
if (caseInsensitive) {
flags |= Pattern.CASE_INSENSITIVE;
}
this.compiled = Pattern.compile(regex, flags);
}
/**
* Check the first operand matches the regex specified as the second operand.
*
* @param state the expression state
* @return {@code true} if the first operand matches the regex specified as the
* second operand, otherwise {@code false}
* @throws EvaluationException if there is a problem evaluating the expression
* (e.g. the regex is invalid)
*/
@Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
SpelNodeImpl leftOp = getLeftOperand();
SpelNodeImpl rightOp = getRightOperand();
Object left = leftOp.getValue(state, String.class);
Object right = getRightOperand().getValueInternal(state).getValue();
if (!(left instanceof String)) {
throw new SpelEvaluationException(leftOp.getStartPosition(),
SpelMessage.INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR, left);
}
if (!(right instanceof String)) {
throw new SpelEvaluationException(rightOp.getStartPosition(),
SpelMessage.INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR, right);
}
try {
String leftString = (String) left;
String rightString = (String) right;
Pattern pattern = this.patternCache.get(rightString);
if (pattern == null) {
pattern = Pattern.compile(rightString);
this.patternCache.putIfAbsent(rightString, pattern);
}
Matcher matcher = pattern.matcher(leftString);
return BooleanTypedValue.forValue(matcher.matches());
} catch (PatternSyntaxException ex) {
throw new SpelEvaluationException(rightOp.getStartPosition(), ex, SpelMessage.INVALID_PATTERN, right);
}
}
/**
* Validate that {@code jsonPathRegex} contains a valid Java regular expression of a {@code
* JsonPath} (Starts with "/", ends with either "/" or "/i", contains a valid Java regular
* expression between "/").
*
* <p>As written, this function will accept the strings "/" and "/i" as complete expressions –
* resulting in an empty inner Java regular expression.
*
* @throws BatfishException if the content of {@code jsonPathRegex} is not a valid Java regular
* expression of a JsonPath.
*/
static void validateJsonPathRegex(String jsonPathRegex) throws BatfishException {
if (!jsonPathRegex.startsWith("/")) {
throw new BatfishException(
String.format(
"A Batfish %s must start with \"/\"", Variable.Type.JSON_PATH_REGEX.getName()));
}
if (!(jsonPathRegex.endsWith("/") || jsonPathRegex.endsWith("/i"))) {
throw new BatfishException(
String.format(
"A Batfish %s must end in either \"/\" or \"/i\"",
Variable.Type.JSON_PATH_REGEX.getName()));
}
String innerPath = "";
if (jsonPathRegex.lastIndexOf('/') > 0) {
innerPath = jsonPathRegex.substring(1, jsonPathRegex.lastIndexOf('/'));
}
try {
Pattern.compile(innerPath);
} catch (PatternSyntaxException e) {
throw new BatfishException(
String.format(
"Invalid %s at interior of %s",
Variable.Type.JAVA_REGEX.getName(), Variable.Type.JSON_PATH_REGEX.getName()),
e);
}
}
/**
* Catch {@link PatternSyntaxException} in dialog & show warning. You can do this by <code>
* View.getSingleton().showWarningDialog(message)</code>.
*
* @param payloadPattern
* @throws PatternSyntaxException
*/
public void setPayloadPattern(String payloadPattern) throws PatternSyntaxException {
if (payloadPattern == null || payloadPattern.length() == 0) {
this.payloadPattern = null;
} else {
this.payloadPattern = Pattern.compile(payloadPattern, Pattern.MULTILINE);
}
}
/**
* Construct a Regular expression from the given {@code source} and {@code flags} strings.
*
* @param source RegExp source string
* @param flags RegExp flag string
* @throws ParserException if flags is invalid or source string has syntax error.
*/
public JdkRegExp(final String source, final String flags) throws ParserException {
super(source, flags);
int intFlags = 0;
if (isIgnoreCase()) {
intFlags |= CASE_INSENSITIVE | UNICODE_CASE;
}
if (isMultiline()) {
intFlags |= MULTILINE;
}
try {
RegExpScanner parsed;
try {
parsed = RegExpScanner.scan(source);
} catch (final PatternSyntaxException e) {
// refine the exception with a better syntax error, if this
// passes, just rethrow what we have
Pattern.compile(source, intFlags);
throw e;
}
if (parsed != null) {
this.pattern = Pattern.compile(parsed.getJavaPattern(), intFlags);
this.groupsInNegativeLookahead = parsed.getGroupsInNegativeLookahead();
}
} catch (final PatternSyntaxException e2) {
throwParserException("syntax", e2.getMessage());
}
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param regex regular expression to match against attribute values. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsByAttributeValueMatching(key, pattern);
}
private static List<PathMatcher> createPathMatchers(FileSystem fs, List<String> patterns) {
List<PathMatcher> matchers = new ArrayList<>();
for (String pattern : patterns) {
try {
matchers.add(fs.getPathMatcher("glob:" + pattern));
} catch (PatternSyntaxException e) {
Log.error("Invalid pattern: " + pattern);
throw e;
}
}
return matchers;
}
private List<TreeItem<Item>> searchItems(String text) {
PathMatcher pathMatcher = null;
try {
String syntaxAndPattern = String.format("glob:**%s**", text);
pathMatcher = FileSystems.getDefault().getPathMatcher(syntaxAndPattern);
} catch (PatternSyntaxException psex) {
return new ArrayList<>();
}
final PathMatcher finalPathMatcher = pathMatcher;
Optional.ofNullable(searchFoundItem)
.map(TreeItem::getValue)
.map(Item::getPath)
.filter(p -> !finalPathMatcher.matches(p))
.ifPresent(p -> searchFoundItem = null);
if (Objects.nonNull(searchFoundItem)) {
if (!pathItemMap.containsValue(searchFoundItem)) {
searchFoundItem = null;
}
}
return pathItemMap.values()
.stream()
.map(e -> Optional.ofNullable(e))
.filter(o -> o
.map(TreeItem::getValue)
.map(Item::getPath)
.filter(p -> !p.equals(p.getRoot()))
.filter(p -> finalPathMatcher.matches(p))
.isPresent())
.map(e -> e.get())
.sorted((p1, p2) -> pathOrder.comparePaths(p1.getValue().getPath(), p2.getValue().getPath()))
.collect(Collectors.toList());
}