- 积分
- 23
- 注册时间
- 2010-11-7
- 仿真币
-
- 最后登录
- 1970-1-1
|
发表于 2013-7-1 14:44:58
|
显示全部楼层
来自 北京
本帖最后由 liuyalong008 于 2013-7-1 14:51 编辑
qibbxxt 发表于 2013-6-30 23:22
本题目的不能用\的原因,来自己第三个例子的_和-1,将这两个替换掉,可以这样做,有点投机取巧之嫌,但也不 ...
其实qi版用a来代替-1还不如用一个数字来代替可能会更好,防止a开头的单词的混淆- regexpi(regexprep(inStr,{'_','-1'},{' ','5'}),'(\<\w)[\w-]*(\1\>)','match')
复制代码 我也仿照着来一个:- regexpi(regexp(inStr,'[,_\s\.]','split'),'(\<\w).*\1,'match')
- [ans{:}]
复制代码 按照空格、下划线和点号把字符串分割然后对每个子串进行首字母和尾字母的匹配,缺点是还需要在提取一次
我个人很喜欢作者给出的solution和他的remarks:- function output = getWordsSameStartEnd( inStr )
-
- % No "ans" trick, so it is still
- % possible to take the lead!
- % I built this problem to test..
- % - 'tokens' with the requirement
- % of matching 1st and last letters.
- % - 'lookarounds' with the annoying
- % requirement about underscores not
- % being letters (so we cannot use
- % \<\> directly).
-
- output = regexpi(inStr, '(?<=(^|\W|_))(?<start>[a-zA-Z])[\w-]*?\k<start>(?=($|[\s,_]))', 'match') ;
- end</pre>
复制代码 (?<=(^|\W|_))依旧是look around的匹配单词之前的条件
(?<start>[a-zA-Z])[\w-]*?\k<start>相当精妙
(?<start>[a-zA-Z])具体用法可参照#24~#28
[a-zA-Z]找出首字母,当然nwcwww的帖子的提醒regexpi中用[a-z]也可
[\w-]*?尽可能短地匹配中间的字母
\k<start>为匹配token?<start>的内容,一般用法是\k<name>
此solution总体感觉很清爽易懂
也可以把tokens,names 也都输出看看- [m,t,n]=regexpi(inStr, '(?<=(^|\W|_))(?<start>[a-z])[\w-]*?\k<start>(?=($|[\s,_]))', 'match','tokens','names')
复制代码 此外,大小写不敏感在matlab正则表达式中有三种方式:- '(?i)'
- regexp(inStr, '(?i)(?<=(^|\W|_))(?<start>[a-z])[\w-]*?\k<start>(?=($|[\s,_]))', 'match')
- 也可以用
- regexpi,
- 或者
- regexp(str,expression,'match','ignorecase')
复制代码 |
评分
-
1
查看全部评分
-
|