Is there a simple approach to adding spaces before and after every number in a cell array, where each cell is a combination of numbers and letters?

Hello,
I have an [m x n] cell in the range of thousands. For simplicity, let's deal with a 2x3 cell instead. The elements are as follows:
{[123xswqe412]} {[xasdak12399a8s]} {[123123xq13]}
{[qasoasf1231]} {[asd11skka13551]} {[127u8adkja]}
Can you please advise on how I can make it so that the output is as follows:
{[123 xswqe 412]} {[xasdak 12399 a 8 s]} {[123123 xq 13]}
{[qasoasf 1231]} {[asd 11 skka 13551]} {[127 u 8 adkja]}
Any help would be appreciated!
Thanks in advance!

댓글 수: 1

That's almost assuredly a regexpr job but beyond my pay grade to try to write the expression! :)

댓글을 달려면 로그인하십시오.

 채택된 답변

I don't know why I took the time to do this and my function separating the words is super ugly but I think you want something like this:
% string
str = '123xswqe412ew3';
% regular expression to separate string from number
expr = '\d+|\D+';
%create cell with strings
mycell = cell(50, 1);
mycell(:) = {str};
% perform function on cell
mycell(:) = cellfun(@(x)doRegExp(x, expr), mycell, 'UniformOutput', false);
% function to separate strings
function f = doRegExp(str, expr)
ind = regexp(str, expr);
f = str(ind(1):ind(2)-1);
for i = 2:length(ind)-1
a = str(ind(i):ind(i+1)-1);
f = [f, ' ', a];
end
f = [f, ' ', str(ind(i+1):end)];
end

댓글 수: 4

Hi Jasper,
Thanks a lot! The code works really well!
Quick follow-up question: if I had a period (.) in the string, how can I make the code ignore this? Say instead of 123xswqe412ew3 I now have 123xswqe412ew3.6ajj, and I want to have '3.6 ajj' in the end instead
ind = regexp(str, '\d+[\.]\d+|\D+|\d+', 'match')
I added an extra OR statement basically to check for digits with dots in between. And maybe this match option in regexp is actually an easier way of splitting your string.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

I'll just go ahead and give an alternative answer because I spent way too much time trying to solve this seemingly easy problem :)
clear all;
str='1.23AB.C44444OA43872AX5';
[ind11,ind12] = regexp(str, '\d[A-Za-z]');
[ind21,ind22] = regexp(str, '[A-Za-z]\d');
ind=sort([ind11 ind12 ind21 ind22])
chars=str(ind)
str=regexprep(str,'\d[A-Za-z]','X X')
str=regexprep(str,'[A-Za-z]\d','X X')
ind3=regexp(str,'X')
str(ind3)=chars
I tried solving the problem with '.', as mentioned in the comment. Unfortunately a new bug appeared, where substrings like 21.FP will not be split. Not sure how to solve that though.

댓글 수: 1

Thank you! That's fine since I don't think I'll ever need a letter immediately after a dot. Thanks again!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

태그

질문:

2018년 5월 4일

댓글:

2018년 5월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by