MATLAB 正则表达式regexp函数使用

本文深入解析MATLAB中的正则表达式regexp函数,包括返回字符串位置、匹配字符串、分割字符串等多种使用方法,适用于不同场景的数据处理需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文介绍MATLAB正则表达式regexp函数常见使用方法。

  1. startIndex = regexp(str,expression)
    这个语句会返回所有符合条件的字符串的第一个字符的位置,注意是所有符合的。
str = 'bat cat can car coat court CUT ct CAT-scan';
expression = 'c[aeiou]+t';
startIndex = regexp(str,expression)

在这里插入图片描述
2. [startIndex,endIndex] = regexp(str,expression)
这个语句返回起始位置和结束位置,注意是所有符合的。

在这里插入图片描述
注意: 如果输入为元胞数组,那么返回的也是元胞数组,例如:

str = {'Madrid, Spain','Romeo and Juliet','MATLAB is great'};
capExpr = '[A-Z]';
capStartIndex = regexp(str,capExpr);

在这里插入图片描述
3. matchStr = regexp(str,expression,‘match’)
用于返回符合条件的字符串,而不是索引。 ‘match’是取词。

str = 'EXTRA! The regexp function helps you relax.';
expression = '\w*x\w*';
matchStr = regexp(str,expression,'match')


4. splitStr = regexp(str,expression,‘split’)
用于在指定位置将字符串分开

str = ['Split ^this text into ^several pieces'];
expression = '\^';
splitStr = regexp(str,expression,'split') % 在有^处分割

在这里插入图片描述
5. [match,noMatch] = regexp(str,expression,‘match’,‘split’)
同时利用’match’和’split’两种方式,用两个输出参数接收,第一个为符合条件的字符串,第二个为剩下的字符串,由符合条件的字符串作为分割界限。

str = 'She sells sea shells by the seashore.';
expression = '[Ss]h.';
[match,noMatch] = regexp(str,expression,'match','split')

在这里插入图片描述
6. [tokens,matches] = regexp(str,expression,‘tokens’,‘match’)
tokens返回捕获的字符串,matches返回匹配的字符串。

str = '<title>My Title</title><p>Here is some text.</p>';
expression = '<(\w+).*>.*</\1>';
[tokens,matches] = regexp(str,expression,'tokens','match');

在这里插入图片描述
从上图总我们可以看到,tokens返回的是括号中捕获到的内容,而matches返回的是符合整个表达式字符串。

  1. matchWithIgnorecase = regexp(str,expression,‘match’,‘ignorecase’)
    ignorecase 这个参数用来指定不区分大小写的。

  2. tokenNames = regexp(str,expression,‘names’);
    用于给捕获到的字符串命名,最后用结构体存储。

str = '01/11/2000  20-02-2020  03/30/2000  16-04-2020';
expression = ['(?<month>\d+)/(?<day>\d+)/(?<year>\d+)|'...
              '(?<day>\d+)-(?<month>\d+)-(?<year>\d+)'];
tokenNames = regexp(str,expression,'names');  % ?<name> 是将符合这个表达式的字符串命名为name

在这里插入图片描述
正则表达式的详细使用方法请见

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肆拾伍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值