下面列出了java.util.regex.Pattern#quote ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException {
if (findString.isEmpty()) {
findString = "^$";
regex = true;
}
int elementCount = elementType.getElementCount(graph);
String searchString = regex ? findString : Pattern.quote(findString);
int caseSensitivity = ignorecase ? Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE : 0;
Pattern searchPattern = Pattern.compile(searchString, caseSensitivity);
for (Attribute a : selectedAttributes) {
for (int i = 0; i < elementCount; i++) {
int currElement = elementType.getElement(graph, i);
String value = graph.getStringValue(a.getId(), currElement);
if (value != null) {
Matcher match = searchPattern.matcher(value);
String newValue = match.replaceAll(replaceString);
if (!newValue.equals(value)) {
graph.setStringValue(a.getId(), currElement, newValue);
}
}
}
}
}
@Override
public List<Filter> getDefaultFilters(SipProfile acc) {
ArrayList<Filter> filters = new ArrayList<Filter>();
Filter f = new Filter();
f.account = (int) acc.id;
f.action = Filter.ACTION_REPLACE;
f.matchPattern = "^"+Pattern.quote("+")+"(.*)$";
f.replacePattern = "00$1";
f.matchType = Filter.MATCHER_STARTS;
filters.add(f);
f = new Filter();
f.account = (int) acc.id;
f.action = Filter.ACTION_REPLACE;
f.matchPattern = "^"+Pattern.quote("011")+"(.*)$";
f.replacePattern = "00$1";
f.matchType = Filter.MATCHER_STARTS;
filters.add(f);
return filters;
}
public UriTemplate(String pathString) {
Preconditions.checkNotNull(pathString);
this.pathString = pathString;
String re = Pattern.quote(Utils.removeLeadingAndTrailingSlash(pathString));
re = re.replaceAll("(^\\\\Q|\\\\E$)", "");
re = "^\\/*" + re + "\\/*$";
re = regexReplaceAll(re, PARAMNAME_REGEX, new Function<MatchResult, String>() {
@Override
public String apply(MatchResult match) {
paramNames.add(match.group(1));
return QUERYPARAM_REGEX;
}
});
regex = Pattern.compile(re, Pattern.CASE_INSENSITIVE);
}
@Test
public void testExecuteIngestAndUpdateWithWorkingDirPutToAttribute() throws IOException {
File exJar = new File("src/test/resources/ExecuteCommand/TestIngestAndUpdate.jar");
File dummy = new File("src/test/resources/ExecuteCommand/1000bytes.txt");
String jarPath = exJar.getAbsolutePath();
exJar.setExecutable(true);
final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
controller.setValidateExpressionUsage(false);
controller.enqueue(dummy.toPath());
controller.setProperty(ExecuteStreamCommand.WORKING_DIR, "target");
controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
controller.setProperty(ExecuteStreamCommand.PUT_OUTPUT_IN_ATTRIBUTE, "streamOutput");
controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
controller.run(1);
controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP);
String result = flowFiles.get(0).getAttribute("streamOutput");
final String quotedSeparator = Pattern.quote(File.separator);
assertTrue(Pattern.compile(quotedSeparator + "nifi-standard-processors" + quotedSeparator + "target:ModifiedResult\r?\n").matcher(result).find());
}
public PsCommand(String processName) {
super("toolbox ps");
this.processName = processName;
pids = new ArrayList<String>();
/**
* regex to get pid out of ps line, example:
*
* <pre>
* root 24736 1 12140 584 ffffffff 40010d14 S /data/data/org.adaway/files/blank_webserver
* ^\\S \\s ([0-9]+) .* processName $
* </pre>
*/
psRegex = "^\\S+\\s+([0-9]+).*" + Pattern.quote(processName) + "$";
psPattern = Pattern.compile(psRegex);
}
PlainLoggerLogic(HudsonJob job, String jobName) {
this.job = job;
// XXX support Windows build servers (using backslashes)
String jobNameQ = Pattern.quote(jobName);
hyperlinkable = Pattern.compile("\\s*(?:\\[.+\\] )?/.+?/(?:jobs/" + jobNameQ + "/workspace|workspace/" + jobNameQ + // NOI18N
")/([^:]+):(?:\\[?([0-9]+)[:,](?:([0-9]+)[]:])?)? (?:warning: )?(.+)"); // NOI18N
}
private static String generatePattern(String delim) {
/*
* Split on the delimiter only if that delimiter has zero, or an
* even number of quotes ahead of it.
*/
return "\\s*" + Pattern.quote(delim) + "\\s*(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
}
private boolean isSep1(Template template, Pattern sep1Line, String line) {
final var sep1LineMatcher = sep1Line.matcher(line);
if (sep1LineMatcher.matches()) {
template.sep1 = Pattern.quote(sep1LineMatcher.group(1));
return true;
}
return false;
}
/**
* On some items such as jobs.
* If some of these happen to be {@link ItemGroup}s, the grant is <em>not</em> applied to children.
*/
public GrantOn onItems(Item... items) {
String[] paths = new String[items.length];
for (int i = 0; i < items.length; i++) {
paths[i] = Pattern.quote(items[i].getFullName());
}
return onPaths(paths);
}
@Override
public RollMode get(String fileName, String periodicPattern) {
fileName = Paths.get(fileName).getFileName().toString();
int tokenStart = fileName.indexOf(getTokenForPattern());
int tokenEnd = tokenStart + getTokenForPattern().length();
String preToken = fileName.substring(0, tokenStart);
String postToken = fileName.substring(tokenEnd);
String name = Pattern.quote(preToken) + periodicPattern + Pattern.quote(postToken);
return new PeriodicRollMode(name);
}
@Test
@InSequence(20)
public void testCombined() throws Exception {
String regexp = REGEX_IP4 + " - - \\[" + REGEX_TIMESTAMP + "\\] \"" +
Pattern.quote("GET " + REQUEST_1_RESOURCE + " HTTP/1.1") +
"\" [0-9]+ [0-9]+ .*";
assertRegexpMatches(regexp, getRequestLogs1().getCombined());
}
private String tokenizeParameters(String str) {
Set<String> variableTokens = ActionUtils.getVariableNames(action);
int tokenCounter = 0;
for (String var : variableTokens) {
String varPattern = Pattern.quote("${") + var + "(\\|.*?)?" + Pattern.quote("}");
str = str.replaceAll(varPattern, Matcher.quoteReplacement("${" + (tokenCounter++) + "}"));
}
return str;
}
@Override
public String remove(String input, String found) {
if (language.equals(LANGUAGES.DE)){
found = "(vom |von |)(dem |der |das |die |)(album|platte) " + Pattern.quote(found);
}else{
found = "(of |from |)(the |a |)(album|record) " + Pattern.quote(found);
}
return NluTools.stringRemoveFirst(input, found);
}
public static DelimitationStrategy of(char paramSeparator) {
// 0 is a blank value of param separator
if (paramSeparator == 0) {
return DelimitationStrategy.NONE;
}
return new DelimitationStrategy(Pattern.quote(String.valueOf(paramSeparator)));
}
private VariableBinding(String variableName, Object value) {
this.pattern = Pattern.quote("$" + variableName);
this.value = Objects.toString(value);
}
public List<String> getJarFilesLocations(List<String> filenames) {
List<String> locations = new ArrayList<>();
for (String filename : filenames) {
// try exact match
JarFileInfo jarLib = jarFiles.stream()
.filter(jfi -> jfi.getSimpleName().contains("!"))
.filter(jfi -> jfi.getSimpleName().split("!")[1].equals("lib_" + filename))
.findFirst().orElse(null);
if (jarLib == null) {
// try artifact name search only
String regex = "^.*!lib_" + Pattern.quote(filename) + "-[^/]+\\.jar$";
List<JarFileInfo> matchedFiles = jarFiles.stream().filter(jfi -> jfi.getSimpleName().matches(regex))
.collect(Collectors.toList());
if (matchedFiles.size() == 1) {
jarLib = matchedFiles.get(0);
} else if (matchedFiles.size() > 1) {
// multiple matches, select one with the shortest name
jarLib = matchedFiles.stream().min(Comparator.comparingInt(jfi -> jfi.getSimpleName().length()))
.orElseThrow(() -> new RuntimeException("Could not find library with shortest name"));
// logging should be initialized by now
Logger log = Logger.getLogger(EeClassLoader.class.getSimpleName());
log.severe(String.format("Multiple jar files with artifact name similar to '%s' found ([%s]). " +
"Using %s. Consider matching by full name.",
filename,
matchedFiles.stream().map(jfi -> jfi.getSimpleName().split("!")[1].substring(4))
.collect(Collectors.joining(", ")),
jarLib.getSimpleName().split("!")[1].substring(4))
);
}
// else exception is thrown because jarLib == null
}
if (jarLib == null) {
throw new IllegalArgumentException("Could not locate library " + filename);
}
locations.add(jarLib.getFileDeleteOnExit().getAbsolutePath());
}
return Collections.unmodifiableList(locations);
}
private AbstractLookup(String startTag, String endTag) {
this.regex = ".*" + Pattern.quote(startTag) + ".*" + Pattern.quote(endTag) + ".*";
this.pattern = Pattern.compile(this.regex);
this.startTag = startTag;
this.endTag = endTag;
}
@Override
@SuppressWarnings("fallthrough")
public void computeTypeNames(Context context, Result result) {
StringBuilder pattern = new StringBuilder();
boolean sensitive = true;
String quotedText = Pattern.quote(context.getText());
switch (context.getSearchType()) {
case CASE_INSENSITIVE_EXACT_NAME:
sensitive = false;
case CAMEL_CASE:
pattern.append(Queries.createCamelCaseRegExp(context.getText(), null, null, sensitive));
break;
case CASE_INSENSITIVE_CAMEL_CASE:
sensitive = false;
pattern.append(Queries.createCamelCaseRegExp(context.getText(), null, null, sensitive));
break;
case EXACT_NAME:
pattern.append("^").append(quotedText).append("$"); // NOI18N
break;
case CASE_INSENSITIVE_PREFIX:
sensitive = false;
case PREFIX:
pattern.append("^").append(quotedText); // NOI18N
break;
case CASE_INSENSITIVE_REGEXP:
sensitive = false;
case REGEXP:
pattern.append(
NameMatcherFactory.wildcardsToRegexp(
JavaTypeProvider.removeNonJavaChars(context.getText()),
false
)
);
break;
}
Pattern searchPattern = Pattern.compile(
pattern.toString(),
Pattern.MULTILINE +
(sensitive ? 0 : Pattern.CASE_INSENSITIVE));
for (Map.Entry<FileObject, OpenProjectFastIndex.NameIndex> one : fastIndex.copyIndexes().entrySet()) {
FileObject root = one.getKey();
Project p = FileOwnerQuery.getOwner(root);
if (context.getProject() != null && !context.getProject().equals(p)) {
continue;
}
OpenProjectFastIndex.NameIndex fileIndex = one.getValue();
Matcher m = searchPattern.matcher(fileIndex.files());
while (m.find()) {
if (cancel.get()) {
LOG.fine("Search canceled");
return;
}
if (m.start() == m.end()) {
continue;
}
CharSequence f = fileIndex.getFilename(m.start(), m.end());
CharSequence pkg = fileIndex.findPath(m.start());
SimpleDescriptor desc = new SimpleDescriptor(p, root, f, pkg);
result.addResult(desc);
}
}
}
/**
* 正規表現に指定する文字列をエスケープした文字列に変換します。
* @see Pattern#quote(java.lang.String)
* @param text 正規表現のパターン
* @return エスケープされた文字列
*/
public static String escapeRegex(CharSequence text) {
return Pattern.quote(text.toString());
}
/**
* For each message such as "Not a good use of {0}", replace the place
* holder {0} with a wild card that matches all possible strings.
* Also put the any non-place-holder in quotes for regex matching later.
*/
private Pattern replacePlaceHolders(String s) {
s = Pattern.quote(s);
return Pattern.compile(s.replaceAll("\\{\\d+\\}", "\\\\E.*\\\\Q"));
}