下面列出了java.util.regex.Matcher#replaceAll ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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("_");
}
@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);
}
/**
* 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;
}
/**
* 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;
}
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());
}
/**
* 去除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(); //返回文本字符串
}
@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 ");
}
private static String convertParametersToVertx(String path) {
Matcher pathMatcher = PATH_PARAMETERS.matcher(path);
while (pathMatcher.find()) {
checkParameterName(pathMatcher.group());
}
return pathMatcher.replaceAll(":$1");
}
protected final String cleanLoggerName(String loggerName) {
Matcher matcher = PATTERN.matcher(loggerName);
if (matcher.find()) {
return matcher.replaceAll("_");
} else {
return loggerName;
}
}
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);
}
}
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);
}
@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;
}
}
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);
}
/**
* 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$
}
@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));
}
}
}
/**
* 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;
}
private String getTableName(String modelName) {
Pattern pattern = Pattern.compile("[^a-z0-9A-Z]");
Matcher matcher = pattern.matcher(modelName);
return matcher.replaceAll("_");
}
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
Matcher m = regex_pattern.matcher(s);
return m.replaceAll(replacement);
}
/**
* 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. <X> and </X>) <li>
* [font COLOR], where COLOR represents any valid html color (i.e. color
* name or hexcode preceeded by #) will be filtered into <font
* color="COLOR"/> <li>[/font] will be filtered into </font> <li>
* [table CLASS], where CLASS gives the style class to use, will be filter
* into <table class="CLASS"/> <li>[/table] will be filtered into
* </table> <li>[td CLASS], where CLASS gives the style class to use,
* will be filter into <td class="CLASS"/>
*
* @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;
}
/**
* 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;
}