正则表达式与文件格式化处理

简单地说,正则表达式就是处理字符串的方法,它以行为单位来进行字符串的处理操作,正则表达式通过一些特殊符号的辅助,可以让用户轻易地完成【查找、删除、替换】某特定字符串的处理过程。

正则表达式基本上是一种【表示法】,只要程序支持这种表示法,那么该程序就可以用来作为正则表达式的字符串处理之用。

一、基础正则表达式

既然正则表达式是处理字符串的一种表示方式,那么对字符排序有影响的语系数据就会对正则表达式的结果有影响。

1.1、语系对正则表达式的影响

使用正则表达式时,需要特别留意当时环境的语系是什么,否则可能会发现与别人不相同的选取结果。

为了避免编码所造成的英文与数字的选取问题,有以下特殊字符
在这里插入图片描述

1.2、grep的一些高级选项

grep [-A] [-B] [--color=auto] '查找字符' filename
选项与参数:
-A:后面可加数字,为after的意思,除了列出该行外,后续的n行也列出来
-B:后面可加数字,为before的意思,除了列出该行外,前面的n行也列出来
-color=auto:可将正确的那个选取列出颜色

1.3、基础正则表达式练习

练习环境:

  1. 语系已经使用【export LANG=C;export LC_ALL=C】的设置值
  2. grep已经使用alias设置成为【grep --color=auto】

练习文件下载

wget "http://linux.vbird.org/linux_basic/0330regularex/regular_express.txt"

示例一:查找特定字符串

查找包含'the'字符串的行,且列出行号
[root@VM_0_8_centos ~]# grep -n 'the' regular_express.txt
8:I can't finish the test.
12:the symbol '*' is represented as start.
15:You are the best is mean you are the no. 1.
16:The world <Happy> is the same with "glad".
18:google is the best tools for search keyword.
反向选择
[root@VM_0_8_centos ~]# grep -vn 'the' regular_express.txt
1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
4:this dress doesn't fit me.
5:However, this dress is about $ 3183 dollars.
6:GNU is free air not free beer.
7:Her hair is very beauty.
9:Oh! The soup taste good.
10:motorcycle is cheap than car.
11:This window is clear.
13:Oh!	My god!
14:The gd software is a library for drafting programs.
17:I like dog.
19:goooooogle yes!
20:go! go! Let's go.
21:# I am VBird
22:

忽略大小写
[root@VM_0_8_centos ~]# grep -in "the" regular_express.txt
8:I can't finish the test.
9:Oh! The soup taste good.
12:the symbol '*' is represented as start.
14:The gd software is a library for drafting programs.
15:You are the best is mean you are the no. 1.
16:The world <Happy> is the same with "glad".
18:google is the best tools for search keyword.

示例二:利用中括号[]来查找集合字符

查找包含test和taste的行
[root@VM_0_8_centos ~]# grep -n 't[ae]st' regular_express.txt
8:I can't finish the test.
9:Oh! The soup taste good.

中括号[]里面不论有几个字符,它都仅代表某【一个】字符。

使用集合字符的反向选择[^],获取oo前面没有g的行
[root@VM_0_8_centos ~]# grep -n '[^g]oo' regular_express.txt
2:apple is my favorite food.
3:Football game is not use feet only.
18:google is the best tools for search keyword.
19:goooooogle yes!

获取oo前面没有小写字母的行,使用[:lower:]可以忽略语系对编码的影响
[root@VM_0_8_centos ~]# grep -n '[^a-z]oo' regular_express.txt 
3:Football game is not use feet only.
[root@VM_0_8_centos ~]# grep -n '[^[:lower:]]oo' regular_express.txt 
3:Football game is not use feet only.


获取包含数字的行,使用[:digit:]可以忽略语系对编码的影响
[root@VM_0_8_centos ~]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值