Java Code Examples for java.util.regex.Matcher#replaceFirst()

The following examples show how to use java.util.regex.Matcher#replaceFirst() . 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: WikiTable.java    From yago3 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: JavaVertXServerCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
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;
}
 
Example 3
Source File: ForumCollapseDecoder.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: JavaVertXServerGenerator.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: EngineCase.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: PaginationHelper.java    From blog-spring with MIT License 6 votes vote down vote up
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);
}
 
Example 7
Source File: ImageLoader.java    From RetailStore with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source File: CfTableRepository.java    From mybatis-dalgen with Apache License 2.0 6 votes vote down vote up
/**
 * 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);

    }
}
 
Example 9
Source File: QueryUtils.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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, "");
}
 
Example 10
Source File: KerberosName.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 11
Source File: RegexUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example 12
Source File: ActionUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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()]);
}
 
Example 13
Source File: SwaggerUiProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
 
Example 14
Source File: PostgreSqlToHsqlTranslationDialect.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public String preprocessSql(String sql) {
    Matcher matcher = pattern.matcher(sql);
    if (matcher.find()) {
        sql = matcher.replaceFirst("create ");
    }
    return sql;
}
 
Example 15
Source File: StringUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: Redirect.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
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;
	}
}
 
Example 17
Source File: YoutubeSignatureCipherManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * 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)) + "/");
}
 
Example 18
Source File: KerberosName.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 19
Source File: ParserUtils.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
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;
}
 
Example 20
Source File: GroupHead.java    From floobits-intellij with Apache License 2.0 4 votes vote down vote up
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));
	}
}