Skip to content

Commit bc56e55

Browse files
正则替换
1 parent d4f53cc commit bc56e55

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.regex;
2+
3+
4+
import org.apache.commons.io.FileUtils;
5+
6+
import java.io.File;
7+
import java.io.IOException;
8+
import java.util.regex.Matcher;
9+
import java.util.regex.Pattern;
10+
11+
/**
12+
* 功能: 将 {123} ,替换为 {}
13+
*
14+
* 引入 jar 包:
15+
*
16+
* <dependency>
17+
* <groupId>commons-io</groupId>
18+
* <artifactId>commons-io</artifactId>
19+
* <version>2.4</version>
20+
* </dependency>
21+
*
22+
*/
23+
public class RegexReplaceUtil {
24+
25+
public static void main(String[] args) throws IOException {
26+
String fileName = "E:\\每日复盘模板.txt";
27+
// 原始字符串
28+
String originalString = FileUtils.readFileToString(new File(fileName), "UTF-8");
29+
30+
// 要替换的新内容
31+
String replacement = "";
32+
// 定义正则表达式模式
33+
Pattern pattern = Pattern.compile("\\{([^)]+)}");
34+
// 创建 Matcher 对象
35+
Matcher matcher = pattern.matcher(originalString);
36+
// 存储结果的 StringBuffer
37+
StringBuffer result = new StringBuffer();
38+
// 查找并替换匹配项
39+
while (matcher.find()) {
40+
// 将匹配项替换为新内容
41+
matcher.appendReplacement(result, "{" + replacement + "}");
42+
}
43+
// 追加最后未匹配部分
44+
matcher.appendTail(result);
45+
// 输出结果
46+
System.out.println(result.toString());
47+
}
48+
49+
}

0 commit comments

Comments
 (0)