[改善Java代码]推荐在复杂字符串操作中使用正则表达式

news/2025/2/24 15:29:49

一、分析 

字符串的操作,诸如追加、合并、替换、倒序、分隔等,都是在编码过程中经常用到的,而且Java也提供了append、replace、reverse、split等方法来完成这些操作,它们使用起来确实方便,但是更多的时候,需要使用正则表达式来完成复杂的处理。 

二、场景 

统计一篇文章中的单词的数量,代码如下 

 1 import java.util.Scanner;
 2 
 3 public class Client {
 4     public static void main(String[] args) {
 5         //接收键盘输入
 6         Scanner input = new Scanner(System.in);
 7         while(input.hasNext()){
 8             String str = input.nextLine();
 9             //使用split方法分隔后统计
10             int wordsCount = str.split(" ").length;
11             System.out.println(str + " 单词数:" + wordsCount);
12         }
13     }
14 }

使用split方法根据空格来分隔单词,然后计算分隔后的数组长度,这种方法可靠吗?我们看输出 

Today is Monday 

Today is Monday 单词数:3 

Today is  Monday 

Today is  Monday 单词数:4 

Today is Monday?No! 

Today is Monday?No! 单词数:3 

I'm Ok. 

I'm Ok. 单词数:2 

 

注意到,除了第一个正确外,其它的都是错误的。第二条输入单词"Monday"前有两个空格,第三条输入中"NO"单词的前后没有空格,最后一个输入则没有把连写符号“'”考虑进去,这样统计出来的单词数量肯定错误一堆,那怎样才合理呢? 

可以考虑使用正则表达式,代码如下 

 1 import java.util.Scanner;
 2 import java.util.regex.Matcher;
 3 import java.util.regex.Pattern;
 4 
 5 public class Client {
 6     public static void main(String[] args) {
 7         //接收键盘输入
 8         Scanner input = new Scanner(System.in);
 9         while (input.hasNext()) {
10             String str = input.nextLine();
11             //正则表达式对象
12             Pattern pattern = Pattern.compile("\\b\\w+\\b");//生成匹配器
14             Matcher matcher = pattern.matcher(str);
15             //记录单词数量
16             int wordsCount = 0;
17             //遍历查找匹配,统计单词数量
18             while (matcher.find()) {
19                 System.out.println(matcher.group());
20                 wordsCount++;
21             }
22             System.out.println(str + " 单词数:" + wordsCount);
23         }
24     }
25 }

输出结果:

Today is Monday 单词数:3 
Today is  Monday 
Today is  Monday 单词数:3 
Today is Monday?No! 
Today is Monday?No! 单词数:4 
I'm Ok. 
I'm Ok. 单词数:3 

每项输出都是正确的,而且程序也不复杂,先生成一个正则表达式对象,然后使用匹配器进行匹配,之后通过一个while循环统计匹配的数量。 

需要说明的是,在Java的正则表达式中"\b"表示的是一个单词的边界,它是一个位置界定符,一边为字符或数字,另外一边则非字符或数字.

例如"A"这样的一个输入就有两个边界,即单词"A"的左右位置,这也就说明了为什么要加上"\w"(它表示的是字符或数字)

三、建议 

正则表达式在字符串的查找、替换、剪切、复制、删除等方面都有着非凡的作用,特别是面对大量的文本字符串需要处理(如果需要锤炼大量的LOG日志)时,使用正则表达式可以大幅提高开发效率和系统性能。 

但是正则表达式是一个恶魔,它会使程序难以读懂 

 

 //==================================

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Client {
    public static void main(String[] args) {
        String c = "But I'm not dead yet!";
        Pattern pattern = Pattern.compile("[ [']]");
        Matcher matcher = pattern.matcher(c);
        for(String str:pattern.split(c)){
            System.out.print(str+" ");
        }
    }
}

输出:

But I m not dead yet! 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/DreamDrive/p/5660260.html


http://www.niftyadmin.cn/n/4827477.html

相关文章

Python3的time模块的使用

import time# 1.time() print( python诞生总时间(1970):, time.time())# 2.asctime() print(当前时间:, time.asctime()) # 当前时间# 3.ctime() print(当前时间:, time.ctime())# 4.gmtime() print(接收时间戳(格林威…

JS 动画

纵向展开 <style>*{margin: 0;padding: 0;}div{width: 100px;height: 100px;background: rgb(9, 175, 9);position: fixed;top: 100px;left: 0px;overflow: hidden;} button{height: 30px;width: 50px;margin: 30px;}</style> </head> <body><butt…

JS 运动函数 轮播图

1. 复制标签的语法 <ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul><script>// 复制标签的方式// clone 方式var ul document.querySelector(ul);// 获取标签var li1 document…

Python3的re模块的使用

import re# 2元字符 . ^ $ * ? { } [ ] | ( ) \ # 作用&#xff1a;匹配字符串s hello world # 返回开始位置 下标 print(s.find(llo))# 找到 并替换 print(s.replace(ll, xx))# . 代指一位字符&#xff0c;代指所有字符 除了换行符 \n ci re.findall(w\w{2}l, hello world…

如何在Linux下环境下快速切换工作目录

为什么80%的码农都做不了架构师&#xff1f;>>> 在Linux命令行下&#xff0c;我们经常需要在一个目录下执行某些操作在跳转到另外的目录下&#xff0c;也就是使用我们熟悉的cd命令&#xff0c;基本上接触过命令行的人&#xff0c;第一个认识的命令都是cd&#xff0…

JS 节点 正则表达式

1. 节点操作 基本概念 复制标签,会使用克隆方法 写入标签时,会使用节点操作方法 什么是节点? 整个的HTML文件,其中的所有内容,都视为HTML文件的一个节点对象 可以通过操作这些节点对象,来操作HTML文件 DOM节点:DOM 就是我们 html 结构中一个一个的节点构成的 不光我们的标签…

Python3的random模块的使用

import randomprint(random.random()) # 默认限制在0-1的小数print(random.randint(1, 8)) # 1-8的整数 包含1和8print(random.choice(joe smith)) # 随机选择一个字符print(random.choice([joe, smith])) # 元组中随机选择print(random.randrange(1, 3)) # 1-3的整数&…

探索不同算法实现在MATLAB中解决LASSO问题:投影梯度法、次梯度方法和平滑梯度方法的详细分析与比较

引言 在机器学习和数据科学的世界中&#xff0c;LASSO&#xff08;Least Absolute Shrinkage and Selection Operator&#xff09;问题是一个经常出现的主题。LASSO 是一种线性模型选择和正则化方法&#xff0c;可以增强预测精度和可解释性。我们将用几种不同的方法来解决这个…