java.util.regex.Matcher#replaceFirst ( )源码实例Demo

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

private String camelizePath(String path) {
    String word = path;
    Pattern pattern = Pattern.compile("\\{([^/]*)\\}");
    Matcher matcher = pattern.matcher(word);
    while (matcher.find()) {
        word = matcher.replaceFirst(":" + matcher.group(1));
        matcher = pattern.matcher(word);
    }
    pattern = Pattern.compile("(_)(.)");
    matcher = pattern.matcher(word);
    while (matcher.find()) {
        word = matcher.replaceFirst(matcher.group(2).toUpperCase());
        matcher = pattern.matcher(word);
    }
    return word;
}
 
@Override
public String decode(String content) {
    Pattern pattern = Pattern.compile(REGEX_COLLAPSE);
    Matcher matcher = pattern.matcher(content);
    int index = 0;
    while (matcher.find()) {
        String title = matcher.group(1);
        content = matcher.group(2);
        content = String.format(HTML_COLLAPSE, index, content);
        if (TextUtils.isEmpty(title)) {
            content = String.format(HTML_COLLAPSE_BUTTON, index, index, content);
        } else {
            title = title.substring(1);
            content = String.format(HTML_COLLAPSE_BUTTON_TITLE, index, index, title, title, content);
        }
        content = matcher.replaceFirst(content);
        matcher = pattern.matcher(content);
        index++;
    }
    return content;
}
 
源代码3 项目: vertx-swagger   文件: JavaVertXServerGenerator.java
private String camelizePath(String path) {
    String word = path;
    Pattern p = Pattern.compile("\\{([^/]*)\\}");
    Matcher m = p.matcher(word);
    while (m.find()) {
        word = m.replaceFirst(":" + m.group(1));
        m = p.matcher(word);
    }
    p = Pattern.compile("(_)(.)");
    m = p.matcher(word);
    while (m.find()) {
        word = m.replaceFirst(m.group(2).toUpperCase());
        m = p.matcher(word);
    }
    return word;
}
 
源代码4 项目: blog-spring   文件: PaginationHelper.java
public static void setPageLink(Model model, HttpServletRequest request) {
  String queryString = request.getQueryString();
  if (queryString == null || queryString.isEmpty()) {
    queryString = "page={page}";
  } else {
    Matcher m = pageParamPattern.matcher(queryString);
    if (m.find()) {
      queryString = m.replaceFirst(m.group(1) + "page={page}");
    } else {
      queryString += "&page={page}";
    }
  }
  String pageLink = request.getRequestURI() + "?" + queryString;

  model.addAttribute("pageLink", pageLink);
}
 
源代码5 项目: mybatis-dalgen   文件: CfTableRepository.java
/**
 * Sets cf operation page cdata.
 *
 * @param cdata the cdata
 * @param cfOperation the cf operation
 */
private void setCfOperationPageCdata(String cdata, CfOperation cfOperation) {

    if (cfOperation.getMultiplicity() == MultiplicityEnum.paging) {//分页配置

        String forCount = cdata;
        Matcher selectFromMather = SELECT_FROM_PATTERN.matcher(cdata);
        if(selectFromMather.find()){
            forCount = selectFromMather.replaceFirst("SELECT\n          COUNT(*) AS total \n        FROM\n");
        }

        String cdataCount = forCount.replaceAll(ORDER_BY_PATTERN, REPLACE_TMP);
        int indexof = cdataCount.indexOf(REPLACE_TMP);
        if (indexof > 0) {
            cdataCount = cdataCount.substring(0, indexof).replaceAll(
                    "(?m)^\\s*$" + System.lineSeparator(), "");
        }

        cfOperation.setCdataPageCount(cdataCount);

    }
}
 
源代码6 项目: ignite   文件: QueryUtils.java
/**
 * Creates a count projected query from the given original query.
 *
 * @param originalQry   must not be {@literal null}.
 * @param cntProjection may be {@literal null}.
 * @return a query String to be used a count query for pagination. Guaranteed to be not {@literal null}.
 */
static String createCountQueryFor(String originalQry, @Nullable String cntProjection) {
    Assert.hasText(originalQry, "OriginalQuery must not be null or empty!");

    Matcher matcher = COUNT_MATCH.matcher(originalQry);
    String countQuery;

    if (cntProjection == null) {
        String variable = matcher.matches() ? matcher.group(VARIABLE_NAME_GROUP_INDEX) : null;
        boolean useVariable = variable != null && StringUtils.hasText(variable) && !variable.startsWith("new")
            && !variable.startsWith("count(") && !variable.contains(",");

        String replacement = useVariable ? SIMPLE_COUNT_VALUE : COMPLEX_COUNT_VALUE;
        countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, replacement));
    }
    else
        countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, cntProjection));

    return countQuery.replaceFirst(ORDER_BY_PART, "");
}
 
源代码7 项目: RetailStore   文件: ImageLoader.java
/**
 * If the URL contains a special variable width indicator (eg "__w-200-400-800__")
 * we get the buckets from the URL (200, 400 and 800 in the example) and replace
 * the URL with the best bucket for the requested width (the bucket immediately
 * larger than the requested width).
 */
@Override
protected String getUrl(String model, int width, int height) {
    Matcher m = PATTERN.matcher(model);
    int bestBucket = 0;
    if (m.find()) {
        String[] found = m.group(1).split("-");
        for (String bucketStr : found) {
            bestBucket = Integer.parseInt(bucketStr);
            if (bestBucket >= width) {
                // the best bucket is the first immediately bigger than the requested width
                break;
            }
        }
        if (bestBucket > 0) {
            model = m.replaceFirst("w"+bestBucket);
        }
    }
    return model;
}
 
源代码8 项目: birt   文件: EngineCase.java
/**
 * Replace the given string with a replacement if it matches a certain
 * pattern.
 * 
 * @param str
 * @return filtered string, the tokens that matches the patterns are
 *         replaced with replacement.
 */

protected String filterLine( String str )
{
	String result = str;

	for ( int i = 0; i < FILTER_PATTERNS.length; i++ )
	{
		Pattern pattern = (Pattern) FILTER_PATTERNS[i][0];
		String replacement = (String) FILTER_PATTERNS[i][1];

		Matcher matcher = pattern.matcher( result );
		while ( matcher.find( ) )
		{
			result = matcher.replaceFirst( replacement );
		}
		// result = matcher.replaceAll( replacement );
	}

	return result;
}
 
源代码9 项目: yago3   文件: WikiTable.java
/**
 * Read an attribute of the form name="value" or name=number
 * @param name of the attribute
 * @param attrib containing the input string, and the remaining after removing the attribute
 * @return value of the attribute
 */
private static String getAttrib(String name, Helper attrib) {
  if (attrib.remaining == null) return null;
  Pattern p = attribPattern.computeIfAbsent(name, n -> Pattern.compile("\\b" + Pattern.quote(name) + "=(?<arg>\"[^\"]*\"|\\d*)"));

  Matcher m = p.matcher(attrib.remaining);
  if (m.find()) {
    attrib.remaining = m.replaceFirst("");
    String content = m.group("arg");
    if (content.startsWith("\"") && content.endsWith("\"")) {
      content = content.substring(1, content.length() - 1);
    }
    return content;
  }
  return null;
}
 
源代码10 项目: obevo   文件: PostgreSqlToHsqlTranslationDialect.java
@Override
public String preprocessSql(String sql) {
    Matcher matcher = pattern.matcher(sql);
    if (matcher.find()) {
        sql = matcher.replaceFirst("create ");
    }
    return sql;
}
 
源代码11 项目: substitution-schedule-parser   文件: ParserUtils.java
private static String handleUrlWithHidriveToken(String url, String loginResponse) {
    if (loginResponse == null) return url;
    Pattern hidriveTokenPattern = Pattern.compile("\\{hidrive-token\\}");
    Matcher matcher = hidriveTokenPattern.matcher(url);
    if (matcher.find()) {
        url = matcher.replaceFirst(loginResponse);
    }

    Pattern hidrivePattern = Pattern.compile("\\{hidrive-pid\\(([^)]+)\\)\\}");
    matcher = hidrivePattern.matcher(url);
    if (matcher.find()) {
        String[] path = matcher.group(1).split("/");
        String filename = path[path.length - 1];
        String filepath = String.join("/", Arrays.copyOfRange(path, 0, path.length - 1));

        String apiUrl = "https://my.hidrive.com/api/dir?path=" + filepath + "&fields=members.name%2Cmembers" +
                ".id&members=all&limit=0%2C5000";
        Request request = Request.Get(apiUrl).connectTimeout(1000).socketTimeout(1000)
                .addHeader("Authorization", "Bearer " + loginResponse);
        try {
            JSONObject result = new JSONObject(request.execute().returnContent().asString());
            JSONArray members = result.getJSONArray("members");
            for (int i = 0; i < members.length(); i++) {
                JSONObject file = members.getJSONObject(i);
                if (file.getString("name").equals(filename)) {
                    url = matcher.replaceFirst(file.getString("id"));
                    break;
                }
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }


    return url;
}
 
源代码12 项目: big-c   文件: KerberosName.java
/**
 * Replace the matches of the from pattern in the base string with the value
 * of the to string.
 * @param base the string to transform
 * @param from the pattern to look for in the base string
 * @param to the string to replace matches of the pattern with
 * @param repeat whether the substitution should be repeated
 * @return
 */
static String replaceSubstitution(String base, Pattern from, String to,
                                  boolean repeat) {
  Matcher match = from.matcher(base);
  if (repeat) {
    return match.replaceAll(to);
  } else {
    return match.replaceFirst(to);
  }
}
 
源代码13 项目: lavaplayer   文件: YoutubeSignatureCipherManager.java
/**
 * Produces a valid dash XML URL from the possibly ciphered URL.
 * @param httpInterface HTTP interface instance to use
 * @param playerScript Address of the script which is used to decipher signatures
 * @param dashUrl URL of the dash XML, possibly with a ciphered signature
 * @return Valid dash XML URL
 * @throws IOException On network IO error
 */
@Override
public String resolveDashUrl(HttpInterface httpInterface, String playerScript, String dashUrl) throws IOException {
  Matcher matcher = signatureExtraction.matcher(dashUrl);

  if (!matcher.find()) {
    return dashUrl;
  }

  YoutubeSignatureCipher cipher = getCipherKeyFromScript(httpInterface, playerScript);
  return matcher.replaceFirst("/signature/" + cipher.apply(matcher.group(1)) + "/");
}
 
源代码14 项目: jease   文件: Redirect.java
public String transform(String input) {
	if (pattern == null) {
		pattern = Pattern.compile(source);
	}
	Matcher matcher = pattern.matcher(input);
	if (matcher.matches()) {
		return matcher.replaceFirst(target);
	} else {
		return input;
	}
}
 
源代码15 项目: NGA-CLIENT-VER-OPEN-SOURCE   文件: StringUtils.java
private static String buildAudioHtml(String content) {
    String regex = "\\[flash=audio](.*?)\\[/flash]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(content);
    while (matcher.find()) {
        String audioUrl = matcher.group();
        audioUrl = audioUrl.substring(14, audioUrl.indexOf("[/flash]") - 1);
        // <audio src="http://img.ngacn.cc/attachments/mon_201802/25/-7Q5-ak1cKe.mp3?duration=3&filename=nga_audio.mp3" controls="controls"></audio>
        audioUrl = "<audio src=\"http://img.ngacn.cc/attachments" + audioUrl + "&filename=nga_audio.mp3\" controls=\"controls\"></audio>";
        content = matcher.replaceFirst(audioUrl);
        matcher = pattern.matcher(content);
    }
    return content;
}
 
源代码16 项目: hadoop   文件: KerberosName.java
/**
 * Replace the matches of the from pattern in the base string with the value
 * of the to string.
 * @param base the string to transform
 * @param from the pattern to look for in the base string
 * @param to the string to replace matches of the pattern with
 * @param repeat whether the substitution should be repeated
 * @return
 */
static String replaceSubstitution(String base, Pattern from, String to,
                                  boolean repeat) {
  Matcher match = from.matcher(base);
  if (repeat) {
    return match.replaceAll(to);
  } else {
    return match.replaceFirst(to);
  }
}
 
源代码17 项目: quarkus   文件: SwaggerUiProcessor.java
public String updateApiUrl(String original, String openApiPath) {

        Matcher uriMatcher = SWAGGER_UI_DEFAULT_API_URL_PATTERN.matcher(original);
        if (uriMatcher.matches()) {
            return uriMatcher.replaceFirst("$1" + openApiPath + "$3");
        } else {
            log.warn("Unable to replace the default URL of Swagger UI");
            return null;
        }
    }
 
源代码18 项目: netbeans   文件: ActionUtils.java
/**
 * Map files of one kind in a source directory to files of another kind in a target directory.
 * You may use regular expressions to remap file names in the process.
 * Only files which actually exist in the target directory will be returned.
 * <span class="nonnormative">(If you expect the target files to be created
 * by Ant you do not need this method, since Ant's mappers suffice.)</span>
 * The file paths considered by the regular expression (if supplied) always use
 * <samp>/</samp> as the separator.
 * <p class="nonnormative">
 * Typical usage to map a set of Java source files to corresponding tests:
 * <code>regexpMapFiles(files, srcDir, Pattern.compile("/([^/]+)\\.java"), testSrcDir, "/\\1Test.java", true)</code>
 * </p>
 * @param fromFiles a list of source files to start with (may be empty)
 * @param fromDir a directory in which all the source files reside
 * @param fromRx a regular expression to match against the source files
 *               (or null to keep the same relative file names); only one
 *               match (somewhere in the path) is checked for; failure to match
 *               prevents the file from being included
 * @param toDir a target directory that results will reside in
 * @param toSubst replacement text for <code>fromRx</code> (may include regexp references),
 *                or must be null if <code>fromRx</code> was null
 * @param strict true to return null in case some starting files did not match any target file
 * @return a list of corresponding target files (may be empty), or null if in strict mode
 *         and there was at least one source file which did not match a target file

 * @throws IllegalArgumentException in case some source file is not in the source directory
 */
public static FileObject[] regexpMapFiles(FileObject[] fromFiles, FileObject fromDir, Pattern fromRx, FileObject toDir, String toSubst, boolean strict) throws IllegalArgumentException {
    List<FileObject> files = new ArrayList<FileObject>();
    for (FileObject fromFile : fromFiles) {
        String path = FileUtil.getRelativePath(fromDir, fromFile);
        if (path == null) {
            throw new IllegalArgumentException("The file " + fromFile + " is not in " + fromDir); // NOI18N
        }
        String toPath;
        if (fromRx != null) {
            Matcher m = fromRx.matcher(path);
            toPath = m.replaceFirst(toSubst);
            if (toPath.equals(path) && !m.find(0)) {
                // Did not match the pattern.
                if (strict) {
                    return null;
                } else {
                    continue;
                }
            }
        } else {
            toPath = path;
        }
        FileObject target = toDir.getFileObject(toPath);
        if (target == null) {
            if (strict) {
                return null;
            } else {
                continue;
            }
        }
        files.add(target);
    }
    return files.toArray(new FileObject[files.size()]);
}
 
源代码19 项目: tutorials   文件: RegexUnitTest.java
@Test
public void whenReplaceFirstWorks_thenCorrect() {
    Pattern pattern = Pattern.compile("dog");
    Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
    String newStr = matcher.replaceFirst("cat");
    assertEquals("cats are domestic animals, dogs are friendly", newStr);
}
 
源代码20 项目: floobits-intellij   文件: GroupHead.java
GroupHead(String pattern, final String wholePattern)
		throws InvalidPatternException {
	super(false);
	this.characterClasses = new ArrayList<CharacterPattern>();
	this.inverse = pattern.startsWith("!"); //$NON-NLS-1$
	if (inverse) {
		pattern = pattern.substring(1);
	}
	final Matcher matcher = REGEX_PATTERN.matcher(pattern);
	while (matcher.find()) {
		final String characterClass = matcher.group(0);
		if (characterClass.length() == 3 && characterClass.charAt(1) == '-') {
			final char start = characterClass.charAt(0);
			final char end = characterClass.charAt(2);
			characterClasses.add(new CharacterRange(start, end));
		} else if (characterClass.equals("[:alnum:]")) { //$NON-NLS-1$
			characterClasses.add(LetterPattern.INSTANCE);
			characterClasses.add(DigitPattern.INSTANCE);
		} else if (characterClass.equals("[:alpha:]")) { //$NON-NLS-1$
			characterClasses.add(LetterPattern.INSTANCE);
		} else if (characterClass.equals("[:blank:]")) { //$NON-NLS-1$
			characterClasses.add(new OneCharacterPattern(' '));
			characterClasses.add(new OneCharacterPattern('\t'));
		} else if (characterClass.equals("[:cntrl:]")) { //$NON-NLS-1$
			characterClasses.add(new CharacterRange('\u0000', '\u001F'));
			characterClasses.add(new OneCharacterPattern('\u007F'));
		} else if (characterClass.equals("[:digit:]")) { //$NON-NLS-1$
			characterClasses.add(DigitPattern.INSTANCE);
		} else if (characterClass.equals("[:graph:]")) { //$NON-NLS-1$
			characterClasses.add(new CharacterRange('\u0021', '\u007E'));
			characterClasses.add(LetterPattern.INSTANCE);
			characterClasses.add(DigitPattern.INSTANCE);
		} else if (characterClass.equals("[:lower:]")) { //$NON-NLS-1$
			characterClasses.add(LowerPattern.INSTANCE);
		} else if (characterClass.equals("[:print:]")) { //$NON-NLS-1$
			characterClasses.add(new CharacterRange('\u0020', '\u007E'));
			characterClasses.add(LetterPattern.INSTANCE);
			characterClasses.add(DigitPattern.INSTANCE);
		} else if (characterClass.equals("[:punct:]")) { //$NON-NLS-1$
			characterClasses.add(PunctPattern.INSTANCE);
		} else if (characterClass.equals("[:space:]")) { //$NON-NLS-1$
			characterClasses.add(WhitespacePattern.INSTANCE);
		} else if (characterClass.equals("[:upper:]")) { //$NON-NLS-1$
			characterClasses.add(UpperPattern.INSTANCE);
		} else if (characterClass.equals("[:xdigit:]")) { //$NON-NLS-1$
			characterClasses.add(new CharacterRange('0', '9'));
			characterClasses.add(new CharacterRange('a', 'f'));
			characterClasses.add(new CharacterRange('A', 'F'));
		} else if (characterClass.equals("[:word:]")) { //$NON-NLS-1$
			characterClasses.add(new OneCharacterPattern('_'));
			characterClasses.add(LetterPattern.INSTANCE);
			characterClasses.add(DigitPattern.INSTANCE);
		} else {
			final String message = String.format(MessageFormat.format(
					JGitText.get().characterClassIsNotSupported,
					characterClass));
			throw new InvalidPatternException(message, wholePattern);
		}

		pattern = matcher.replaceFirst(""); //$NON-NLS-1$
		matcher.reset(pattern);
	}
	// pattern contains now no ranges
	for (int i = 0; i < pattern.length(); i++) {
		final char c = pattern.charAt(i);
		characterClasses.add(new OneCharacterPattern(c));
	}
}