java.util.regex.Pattern#quote ( )源码实例Demo

下面列出了java.util.regex.Pattern#quote ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: constellation   文件: ReplacePlugin.java
@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);
                }
            }
        }
    }
}
 
源代码2 项目: CSipSimple   文件: SipCel.java
@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;
}
 
源代码3 项目: RestServices   文件: UriTemplate.java
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());
}
 
源代码5 项目: AOSPBrowserInstaller   文件: Toolbox.java
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);
}
 
源代码6 项目: netbeans   文件: PlainLogger.java
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
}
 
源代码7 项目: ghidra   文件: AbstractRegexBasedTermSplitter.java
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*(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
}
 
源代码8 项目: javageci   文件: Iterate.java
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);
}
 
源代码11 项目: appengine-tck   文件: RequestLogsTest.java
@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());
}
 
源代码12 项目: curly   文件: ActionRunner.java
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;
}
 
源代码13 项目: sepia-assist-server   文件: MusicAlbum.java
@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)));
}
 
源代码15 项目: akka-tutorial   文件: AkkaUtils.java
private VariableBinding(String variableName, Object value) {
	this.pattern = Pattern.quote("$" + variableName);
	this.value = Objects.toString(value);
}
 
源代码16 项目: kumuluzee   文件: EeClassLoader.java
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);
}
 
源代码17 项目: freehealth-connector   文件: RecursiveProperties.java
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;
}
 
源代码18 项目: netbeans   文件: FastTypeProvider.java
@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);
        }
    }
}
 
源代码19 项目: sinavi-jfw   文件: Strings.java
/**
 * 正規表現に指定する文字列をエスケープした文字列に変換します。
 * @see Pattern#quote(java.lang.String) 
 * @param text 正規表現のパターン
 * @return エスケープされた文字列
 */
public static String escapeRegex(CharSequence text) {
    return Pattern.quote(text.toString());
}
 
源代码20 项目: astor   文件: RhinoErrorReporter.java
/**
 * 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"));
}