Java字符串处理实用技巧
立即解锁
发布时间: 2025-08-20 00:06:31 阅读量: 1 订阅数: 3 


Java编程实战:从基础到高级项目
# Java字符串处理实用技巧
## 1. 正则表达式匹配基础
在Java中,使用正则表达式进行字符串匹配是一项常见的任务。可以通过`Matcher`类来应用正则表达式模式到数据上。以下是一个简单的示例:
```java
// get a Matcher to apply the pattern to the data
Matcher nameMatcher = namePattern.matcher(data);
boolean isMatch = nameMatcher.matches();
```
`matches`方法会将整个输入字符串与模式进行匹配。如果只想检查字符串是否以模式开头,可以使用`lookingAt`方法:
```java
boolean startsWith = nameMatcher.lookingAt();
```
后续还会讨论其他匹配技术,如查找匹配模式的子字符串和执行文本替换。
### 1.1 使用`String.split`方法分割字符串
开发者有时需要使用分隔符(如逗号、制表符或空格)将字符串分割成子字符串。Java 1.4引入了`Pattern`类,除了模式匹配外,`Pattern`对象还可以使用正则表达式作为分隔符将字符串分割成子字符串数组。
示例代码如下:
```java
String data = "Australia,Fiji,New Zealand,Papua New Guinea";
Pattern comma = Pattern.compile(",");
String[] countries = comma.split(data);
```
`String`类也有`split`方法,使用起来更方便。下面的代码将分隔符改为包含逗号前后的任意空格:
```java
String data = "Australia, Fiji, New Zealand , Papua New Guinea";
String[] countries = data.split("\\s*,\\s*");
```
这里的正则表达式语法与前面的`Pattern`对象相同,因此`split`方法的用途不止于处理逗号和空格。
### 1.2 在字符串中查找子字符串模式
可以使用正则表达式模式在字符串中查找多个匹配值。以在文档中查找嵌入的URL为例,首先需要一个匹配URL的模式字符串:
```java
String urlString = "(http|https|ftp)://[/\\w\\.\\-\\+\\?%=&;:,#]+";
```
这个模式虽然能匹配大多数常用URL,但也存在一些不足,如会匹配一些无效URL语法的字符串,还可能会捕获额外的字符。
以下是查找文档中所有URL的代码:
```java
String urlString = "(http|https|ftp)://[/\\w\\.\\-\\+\\?%=&;:,#]+";
Pattern urlPattern = Pattern.compile(urlString);
// get the data (somehow)
String data = getStringData();
// get a matcher for the data
Matcher urlMatcher = urlPattern.matcher(data);
// iterate through the matches
while (urlMatcher.find()) {
int startIndex = urlMatcher.start(); // index of start
int endIndex = urlMatcher.end(); // index of end + 1
// retrieve the matching substring
String currentMatch = data.substring(startIndex, endIndex);
System.out.println(currentMatch);
}
```
该代码无法匹配HTML文档中常见的相对URL(如`/images/picture.jpg`)或缺少`http://`前缀的不完整URL。
### 1.3 使用正则表达式捕获组
在前面的例子中,我们可以使用`Matcher`类的`find`、`start`和`end`方法检索匹配的URL字符串。有时需要进一步处理匹配子字符串的结果,例如不处理特定域名的URL。
使用正则表达式捕获组可以更高效地实现这一点。将URL模式重写为:
```java
String urlPattern =
"(http|https|ftp)://([a-zA-Z0-9-\\.]+)[/\\w\\.\\-\\+\\?%=&;:,#]*";
```
在这个模式中,组1是协议(如`http`),组2是域名。以下代码从每个URL中检索域名并打印出来:
```java
String data = getStringData(); // load the document
String urlString =
"(http|https|ftp)://([a-zA-Z0-9-\\.]+)[/\\w\\.\\-\\+\\?%=&;:,#]*";
Pattern urlPattern = Pattern.compile(urlString);
Matcher urlMatcher = urlPattern.matcher(data);
// print out the domain from each URL
while (urlMatcher.find()) {
String domain = urlMatcher.group(2); // 2nd group is the domain
System.out.println(domain);
}
```
正则表达式中的反向引用可以引用之前匹配的组。例如,查找文档中重复单词的模式:
```java
String wordPattern = "\\s(of|or|the|to)\\s+\\1[\\s\\.,;]";
```
以下代码使用不区分大小写的匹配查找模式的出现:
```java
String data = getStringData();
String patternStr = "\\s(of|or|the|to)\\s+\\1[\\s\\.,;]";
Pattern wordPattern =
Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher wordMatcher = wordPattern.matcher(data);
while (wordMatcher.find()) {
int start = wordMatcher.start();
String word = wordMatcher.group(1);
// print the index location of the repeated word
System.out.println("Repeated " + word + " starting at " + start);
}
```
### 1.4 使用正则表达式进行替换
使用正则表达式可以将匹配的模式替换为新的值。`Matcher`类的`replaceAll`方法可以将所有匹配的子字符串替换为给定的字符串参数。
示例代码如下:
```java
String data = getStringData();
Pattern repPattern = Pattern.compile("
```
0
0
复制全文
相关推荐










