How to split a string of digits into groups of three from right-to-left using only regular expressions?

17 次查看(过去 30 天)
While I have been able to accomplish this task using a varitey of mixed functions such as regexp() and fliplr(), I am ultimately stumped when trying to resort to only regexp() and/or regexprep(). For example, I am trying to convert the a string similar to the following:
str = '12345678';
such that the resulting output is:
{'12'} {'345'} {'678'}
I am also trying to accomplish this task without the use of loops of any sort.
  2 个评论
Walter Roberson
Walter Roberson 2020-1-26
Is it permitted to use more than one call to regexp() or regexprep(), or does it need to be just a single call to one or the other?
Is the "execute" group of regexprep() to be permitted?
Allen
Allen 2020-1-27
Single call was preferred, but multiple are acceptable. Was hoping to stay away from the execute groups since that technically uses other functions. However, since I have no experience with trying to generate code using them, I would not have minded seeing a few examples. ;-)

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2020-1-26
编辑:Stephen23 2020-1-27
With one regexp call (uses a lookaround assertion):
>> str = '12345678';
>> regexp(str, '(^\d{1,2}(?=(\d{3})*$)|\d{3})','match')
ans =
'12' '345' '678'
With two regexp calls (splits string into two tokens, may have empty cells in the output):
>> tkn = regexp(str,'^(\d{0,2})((\d{3})*)$','tokens','once');
>> out = [tkn(1),regexp(tkn{2},'\d{3}','match')]
out =
'12' '345' '678'
or with some extra functions to define the regular expression itself:
>> rgx = ['(\d{0,2})',repmat('(\d{3})',1,fix(numel(str)/3))];
>> regexp(str,rgx,'tokens','once')
ans =
'12' '345' '678'
  7 个评论
Allen
Allen 2020-1-27
The first two work perfectly under the limitations. I have been trying to solve that one for quite some time now, but had not been successful with implementing a lookaround assertion to capture more than the first token. Thanks to you both.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by