How to capture an optional expression using regular expressions?
1 次查看(过去 30 天)
显示 更早的评论
Dear all,
I would like to use regular expressions to capture and transform expressions of the form
name
or
name(string,digits)
where name belongs to a list of NAMES and digits is an integer: 1, 2, 3,...
That is, "name" is optionally followed by
- an opening parenthesis: (
- a string
- some numbers : 1, 2, 3,...
- a closing parenthesis: )
For that purpose I wrote the following regular expression that does not work
expr='(\w+)((\w+),(\d+))?'
replace='${convertMe($1,$3,$4)}';
result=regexprep(cellarray,expr,replace)
I have written a convertMe function taking 3 inputs but only the first input gets in. The other inputs the function receives are $3 and $4 instead of the second string and the digits.
Any suggestions?
0 个评论
回答(2 个)
Walter Roberson
2015-9-23
For the longer case, expr='(\w+)(?:\(\w+),\(d+)\))' replace='${convertMe($1,$2,$3)}'
For the case with no argument supplied, it is not clear what you would like passed to convertMe or if you want convertMe to be called at all.
2 个评论
Cedric
2015-9-24
Another option is to parse all entries first, and then to rebuild relevant expressions:
entries = {'name1(John, 48)', 'name2', 'name3(Doo)'} ;
tokens = regexp( entries, '([\w\d_-]+)\(?(\w+)?,?\s*(\d+)?', 'tokens', 'once' ) ;
parsed = vertcat( tokens{:} ) ;
With that you get
>> parsed
parsed =
'name1' 'John' '48'
'name2' '' ''
'name3' 'Doo' ''
which is easy to post process for building whatever you need.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!