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

The following examples show how to use java.util.regex.Matcher#replaceAll() . 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: LoggerExpansion.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
public String getLogFileName() {
    FileConfiguration config = getConfig("logger.yml");
    if(config == null) return "logger.log";

    String fileNameOption = config.getString("log-file-info.file-name");
    if(fileNameOption == null) fileNameOption = "logger";

    String fileExtraFormatOption = config.getString("log-file-info.file-extra.format");
    if(fileExtraFormatOption == null) fileExtraFormatOption = "yyyy.MM.dd";

    String fileExtensionOption = config.getString("log-file-info.file-extension");
    if(fileExtensionOption == null) fileExtensionOption = "log";

    SimpleDateFormat format = new SimpleDateFormat(fileExtraFormatOption);
    Date currentDate = new Date(System.currentTimeMillis());
    String fileNameExtra = format.format(currentDate);

    String preFileName = (fileNameOption + "-" + fileNameExtra + "." + fileExtensionOption);
    Matcher matcher = FILENAME_REGEX.matcher(preFileName);
    return matcher.replaceAll("_");
}
 
Example 2
Source File: StringUtils.java    From BmapLite with Apache License 2.0 6 votes vote down vote up
/**
 * 去除html标签
 * @param htmlStr
 * @return
 */
@NonNull
private static String delHTMLTag(String htmlStr) {
    String regExScript = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
    String regExStyle = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
    String regExHtml = "<[^>]+>"; //定义HTML标签的正则表达式

    Pattern pScript = Pattern.compile(regExScript, Pattern.CASE_INSENSITIVE);
    Matcher mScript = pScript.matcher(htmlStr);
    htmlStr = mScript.replaceAll(""); //过滤script标签

    Pattern pStyle = Pattern.compile(regExStyle, Pattern.CASE_INSENSITIVE);
    Matcher mStyle = pStyle.matcher(htmlStr);
    htmlStr = mStyle.replaceAll(""); //过滤style标签

    Pattern pHtml = Pattern.compile(regExHtml, Pattern.CASE_INSENSITIVE);
    Matcher mHtml = pHtml.matcher(htmlStr);
    htmlStr = mHtml.replaceAll(""); //过滤html标签

    return htmlStr.trim(); //返回文本字符串
}
 
Example 3
Source File: HostTagParser.java    From kairos-carbon with Apache License 2.0 6 votes vote down vote up
@Override
public CarbonMetric parseMetricName(String metricName)
{

	Matcher metricMatcher = m_metricPattern.matcher(metricName);
	if (!metricMatcher.matches())
		return (null);

	CarbonMetric ret = new CarbonMetric(metricMatcher.replaceAll(m_metricReplacement));

	Matcher hostMatcher = m_hostPattern.matcher(metricName);
	if (!hostMatcher.matches())
		return (null);

	ret.addTag("host", hostMatcher.replaceAll(m_hostReplacement));

	return (ret);
}
 
Example 4
Source File: Yago3Util.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
/**
 * Applies cleaning patterns to an entity name.
 *
 * @param entityMention Name to clean.
 * @return  Cleaned name.
 */
public static String cleanEntityMention(String entityMention) {
  Matcher m = CLEAN_P_1.matcher(entityMention);
  entityMention = m.replaceAll("");

  m = CLEAN_P_2.matcher(entityMention);
  entityMention = m.replaceAll(" ");

  m = CLEAN_P_3.matcher(entityMention);
  entityMention = m.replaceAll("");

  m = CLEAN_P_4.matcher(entityMention);
  entityMention = m.replaceAll("");

  return entityMention;
}
 
Example 5
Source File: EditMicroBlogActivity.java    From YiBo with Apache License 2.0 6 votes vote down vote up
public void setGeoLocation(GeoLocation geoLocation) {
	this.geoLocation = geoLocation;
	if (geoLocation == null) {
		return;
	}
	//用最新的坐标替换
	EditText etText  = (EditText)this.findViewById(R.id.etText);
	String status = etText.getEditableText().toString();
	Matcher matcher = pattern.matcher(status);
	if (!matcher.find() && locationListener != null && !locationListener.isAutoLocate()) {
		String locationText = getString(R.string.hint_my_location, geoLocation.getLatitude(), geoLocation.getLongitude());
		etText.setText(status + " " + locationText + " ");
	} else {
		status = matcher.replaceAll(MAP + geoLocation.getLatitude() + "," + geoLocation.getLongitude());
		etText.setText(status);
	}
	etText.setSelection(etText.getEditableText().length());
}
 
Example 6
Source File: UserSearchUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Will change globbing characters to work as expected in Ghidra, unless the
 * special characters are escaped with a backslash.
 *
 * @param input
 *            The string containing potential globbing characters.
 * @return The fixed string
 */
private static String convertGlobbingCharactersToRegex(String input) {
	// NOTE: order is important!

	// replace all unescaped '?' chars
	Matcher questionMatcher = QUESTION_PATTERN.matcher(input);
	String questionReplaced = questionMatcher.replaceAll(".");

	// replace all unescaped '*' chars
	Matcher starMatcher = STAR_PATTERN.matcher(questionReplaced);

	// *? is a Reluctant Quantifier, matching zero or more.  '*' is the quantifier, '?' makes
	// it reluctant
	String starReplaced = starMatcher.replaceAll(".*?");
	return starReplaced;
}
 
Example 7
Source File: KanboardAPI.java    From Kandroid with GNU General Public License v3.0 5 votes vote down vote up
public static URL sanitizeURL(String url) throws MalformedURLException {
    Matcher regexMatcher = urlPattern.matcher(url);
    if (regexMatcher.find()) {
        //URL has filename, replace it
        return new URL(regexMatcher.replaceAll("jsonrpc.php"));
    } else {
        //URL hs no filename, add one
        if (!url.endsWith("/"))
            url += "/";
        url += "jsonrpc.php";
        return new URL(url);
    }
}
 
Example 8
Source File: MentionEditText.java    From TikTok with Apache License 2.0 5 votes vote down vote up
@Override
        public void afterTextChanged(Editable editable) {
            String content = editable.toString();
            if (atBeforeAfter == 1 && !TextUtils.isEmpty(content)) {
                char mentionChar = content.charAt(atBeforeStart);
                if ('@' == mentionChar && mOnMentionInputListener != null) {
                    editable.delete(atBeforeStart,atBeforeStart+1);
                    mOnMentionInputListener.onMentionCharacterInput();
                }
            }

            if(!isCanInputLineFeed && content.contains("\n")){
                Pattern p = Pattern.compile("\r|\n");
                Matcher m = p.matcher(content);
                content = m.replaceAll("");
                editable.replace(0,editable.length(),content,0,content.length());
                if (isShowToast) {
//                    ToastTool.showShort(AppUtil.getApplicationContext(), AppUtil.getApplicationContext().getString(R.string.edit_text_max_length_hint_not_line_feed));
                }
            }
            content = editable.toString();

            if (content.length() > maxEdit) {
                String afterStr = content.substring(beforeStart,beforeStart+beforeAfter);
                int residue = maxEdit - lastText.length();
                if(containsEmoji(afterStr) || afterStr.contains("@") || residue < 0){
                    residue = 0;
                }
                editable.delete(beforeStart + residue,beforeStart + beforeAfter);
                if (isShowToast) {
//                    ToastTool.showShort(AppUtil.getApplicationContext(), AppUtil.getApplicationContext().getString(R.string.edit_text_max_length_hint, maxEdit));
                }
            }

        }
 
Example 9
Source File: SVNMergeUnitFactory.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the repository name of the given {@link String}. If no repository
 * name could be parsed a {@link MergeUnitException} is thrown.
 * 
 * @param fileName the {@link String} to parse
 * @return the repository name
 * @throws MergeUnitException if no repository name could be parsed
 */
private static String getRepositoryName(String fileName) throws MergeUnitException {
	final Matcher matcher = PATTERN_REMOVE_ALL_EXCLUDE_REPONAME.matcher(fileName);
	if (matcher.find()) {
		final String repository = matcher.replaceAll(""); //$NON-NLS-1$
		if (!repository.isEmpty()) {
			return repository;
		}
	}
	throw LogUtil.throwing(new MergeUnitException(
			String.format("No repository identified in the given file name '%s'", fileName))); //$NON-NLS-1$
}
 
Example 10
Source File: GVMTestUtils.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) {

    String[] libraryAddressList = libraryAddressPair.split("[,]");

    for (int i = 0; i < libraryAddressList.length; i++) {
      String cur = libraryAddressList[i];

      int lastPosition = cur.lastIndexOf(":");
      if (-1 == lastPosition) {
        throw new RuntimeException("libraryAddress delimit by ':'");
      }
      String libraryName = cur.substring(0, lastPosition);
      String addr = cur.substring(lastPosition + 1);
      String libraryAddressHex;
      try {
        libraryAddressHex = (new String(Hex.encode(WalletClient.decodeFromBase58Check(addr)),
            "US-ASCII")).substring(2);
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);  // now ignore
      }
      String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_");
      String beReplaced = "__" + libraryName + repeated;
      Matcher m = Pattern.compile(beReplaced).matcher(code);
      code = m.replaceAll(libraryAddressHex);
    }

    return Hex.decode(code);
  }
 
Example 11
Source File: PathSegment.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String interpolationChunk(OptionMap hash) {
    String value = hash.getString(getKey());
    try {
        value = CodecUtils.urlEncode(value);
        Matcher m = ENCODED_SLASH.matcher(value);
        return m.replaceAll("/");
    } catch (Exception e) {
        return value;
    }
}
 
Example 12
Source File: SVMLightRecordWriterTest.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public static void executeTest(Configuration configWriter, Configuration configReader, File inputFile) throws Exception {
    File tempFile = File.createTempFile("SVMLightRecordWriter", ".txt");
    tempFile.setWritable(true);
    tempFile.deleteOnExit();
    if (tempFile.exists())
        tempFile.delete();

    try (SVMLightRecordWriter writer = new SVMLightRecordWriter()) {
        FileSplit outputSplit = new FileSplit(tempFile);
        writer.initialize(configWriter,outputSplit,new NumberOfRecordsPartitioner());
        SVMLightRecordReader rr = new SVMLightRecordReader();
        rr.initialize(configReader, new FileSplit(inputFile));
        while (rr.hasNext()) {
            List<Writable> record = rr.next();
            writer.write(record);
        }
    }

    Pattern p = Pattern.compile(String.format("%s:\\d+ ", SVMLightRecordReader.QID_PREFIX));
    List<String> linesOriginal = new ArrayList<>();
    for (String line : FileUtils.readLines(inputFile)) {
        if (!line.startsWith(SVMLightRecordReader.COMMENT_CHAR)) {
            String lineClean = line.split(SVMLightRecordReader.COMMENT_CHAR, 2)[0];
            if (lineClean.startsWith(" ")) {
                lineClean = " " + lineClean.trim();
            } else {
                lineClean = lineClean.trim();
            }
            Matcher m = p.matcher(lineClean);
            lineClean = m.replaceAll("");
            linesOriginal.add(lineClean);
        }
    }
    List<String> linesNew = FileUtils.readLines(tempFile);
    assertEquals(linesOriginal, linesNew);
}
 
Example 13
Source File: RemovingEmojiFromStringUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenRemoveEmojiUsingMatcher_thenSuccess() {
    Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
    Matcher matcher = pattern.matcher(text);
    
    String result = matcher.replaceAll("");
    System.out.println(result);
    assertEquals(result, "la conférence, commencera à 10 heures ");
}
 
Example 14
Source File: LogAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
protected final String cleanLoggerName(String loggerName) {
    Matcher matcher = PATTERN.matcher(loggerName);
    
    if (matcher.find()) {
        return matcher.replaceAll("_");
    } else {
        return loggerName;
    }
}
 
Example 15
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
private static String convertParametersToVertx(String path) {
    Matcher pathMatcher = PATH_PARAMETERS.matcher(path);

    while (pathMatcher.find()) {
        checkParameterName(pathMatcher.group());
    }

    return pathMatcher.replaceAll(":$1");
}
 
Example 16
Source File: WebUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Excapes out HTML to prevent XSS attacks, and replaces the following
 * strings to allow for a limited set of HTML tags
 * 
 * <li>[X] and [/X], where X represents any 1 or 2 letter string may be used
 * to specify the equivalent tag in HTML (i.e. &lt;X&gt; and &lt;/X&gt;) <li>
 * [font COLOR], where COLOR represents any valid html color (i.e. color
 * name or hexcode preceeded by #) will be filtered into &lt;font
 * color="COLOR"/&gt; <li>[/font] will be filtered into &lt;/font&gt; <li>
 * [table CLASS], where CLASS gives the style class to use, will be filter
 * into &lt;table class="CLASS"/&gt; <li>[/table] will be filtered into
 * &lt;/table&gt; <li>[td CLASS], where CLASS gives the style class to use,
 * will be filter into &lt;td class="CLASS"/&gt;
 * 
 * @param inputString
 * @return
 */
public static String filterHtmlAndReplaceRiceMarkup(String inputString) {
	String outputString = StringEscapeUtils.escapeHtml(inputString);
	// string has been escaped of all <, >, and & (and other characters)

       Map<String, String> findAndReplacePatterns = new LinkedHashMap<String, String>();

       // now replace our rice custom markup into html

       // DON'T ALLOW THE SCRIPT TAG OR ARBITRARY IMAGES/URLS/ETC. THROUGH

       //strip out instances where javascript precedes a URL
       findAndReplacePatterns.put("\\[a ((javascript|JAVASCRIPT|JavaScript).+)\\]", "");
       //turn passed a href value into appropriate tag
       findAndReplacePatterns.put("\\[a (.+)\\]", "<a href=\"$1\">");
       findAndReplacePatterns.put("\\[/a\\]", "</a>");
       
	// filter any one character tags
	findAndReplacePatterns.put("\\[([A-Za-z])\\]", "<$1>");
	findAndReplacePatterns.put("\\[/([A-Za-z])\\]", "</$1>");
	// filter any two character tags
	findAndReplacePatterns.put("\\[([A-Za-z]{2})\\]", "<$1>");
	findAndReplacePatterns.put("\\[/([A-Za-z]{2})\\]", "</$1>");
	// filter the font tag
	findAndReplacePatterns.put("\\[font (#[0-9A-Fa-f]{1,6}|[A-Za-z]+)\\]", "<font color=\"$1\">");
	findAndReplacePatterns.put("\\[/font\\]", "</font>");
	// filter the table tag
	findAndReplacePatterns.put("\\[table\\]", "<table>");
	findAndReplacePatterns.put("\\[table ([A-Za-z]+)\\]", "<table class=\"$1\">");
	findAndReplacePatterns.put("\\[/table\\]", "</table>");
	// fiter td with class
	findAndReplacePatterns.put("\\[td ([A-Za-z]+)\\]", "<td class=\"$1\">");

	for (String findPattern : findAndReplacePatterns.keySet()) {
		Pattern p = Pattern.compile(findPattern);
		Matcher m = p.matcher(outputString);
		if (m.find()) {
			String replacePattern = findAndReplacePatterns.get(findPattern);
			outputString = m.replaceAll(replacePattern);
		}
	}

	return outputString;
}
 
Example 17
Source File: HTMLFilter.java    From kvf-admin with MIT License 4 votes vote down vote up
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
    Matcher m = regex_pattern.matcher(s);
    return m.replaceAll(replacement);
}
 
Example 18
Source File: CompensateServiceImpl.java    From tx-lcn with Apache License 2.0 4 votes vote down vote up
private String getTableName(String modelName) {
    Pattern pattern = Pattern.compile("[^a-z0-9A-Z]");
    Matcher matcher = pattern.matcher(modelName);
    return matcher.replaceAll("_");
}
 
Example 19
Source File: TransformerPropertySetter.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns an array of transformer property names (and optional values).
 * @param text to be parsed
 * @param hasValue values are required, optionally exist when false.
 * @param transformerReferences map of transformerReferences to a line that referenced them.
 * @param dynamicTransformerNames added via properties
 * @return a list of cleaned up transformer properties from the text
 * @throws IllegalArgumentException if an unexpected line is found
 */
private List<String> extractProperties(String text, boolean hasValue, Map<String,
        String> transformerReferences, Set<String> dynamicTransformerNames)
{
    List<String> properties = new ArrayList<String>();
    text = fixJConsolesMissingNewlines(text);
    
    // Split the lines
    Matcher lineMatcher = LINE_SPLIT.matcher(text);
    while (lineMatcher.find())
    {
        String line = lineMatcher.group();
        
        // Strip comments from lines
        Matcher commentMatcher = COMMENT.matcher(line);
        line = commentMatcher.replaceAll("");
        
        // Ignore blank lines
        if (line.length() != 0)
        {
            String lowerLine = line.toLowerCase(); // Should we set the lower case value anyway
            if (lowerLine.startsWith(TransformerConfig.PREFIX))
            {
                checkTransformerProperty(hasValue, line, transformerReferences, dynamicTransformerNames);
                properties.add(line);
            }
            else if (lowerLine.startsWith(TransformerConfig.DEBUG_ENTRIES))
            {
                checkInteger(hasValue, line, TransformerConfig.DEBUG_ENTRIES.length());
                properties.add(line);
            }
            else if (lowerLine.startsWith(TransformerConfig.LOG_ENTRIES))
            {
                checkInteger(hasValue, line, TransformerConfig.LOG_ENTRIES.length());
                properties.add(line);
            }
            else if (lowerLine.startsWith(TransformerConfig.STRICT_MIMETYPE_CHECK_WHITELIST_MIMETYPES))
            {
                checkMimetypeList(hasValue, line, TransformerConfig.STRICT_MIMETYPE_CHECK_WHITELIST_MIMETYPES.length(), true);
                properties.add(line);
            }
            else
            {
                throw unexpectedProperty("Not a transformer property", line);
            }
        }
    }
    
    return properties;
}
 
Example 20
Source File: LdapLoginModule.java    From JDKSourceCode1.8 with MIT License 2 votes vote down vote up
/**
 * Replace the username token
 *
 * @param matcher the replacement pattern
 * @param string the target string
 * @param username the supplied username
 * @return the modified string
 */
private String replaceUsernameToken(Matcher matcher, String string,
    String username) {
    return matcher != null ? matcher.replaceAll(username) : string;
}