MATLAB Answers

Validate and get exact number of characters using the regular expression

69 views (last 30 days)
Bhaskar R
Bhaskar R on 8 Mar 2020
Commented: Bhaskar R on 12 Mar 2020
Hi all,
I am using MATLAB R2016a version and working on a chacters set like
str = 'ENGINE-45'; % this is okay(digits are 2 after hyphen)
where i need to validate and get as numbers of digits after hyphen (-), it should be 2 digtits but in some case it is 3, 4, 5 number digits like
str = 'ACCCAT-455'; % this is not okay(3 digits)
str = 'VCCASNSRR-12344'; % this is not okay(5 digits)
I have used reguler expresion to get charcters and digits as
out_str = regexp(str, '[A-Z]+-[0-9]{2}', 'match');
ans =
'VCCASNSRR-12' % used {2} but where inputs are 5, tryiing to restrict this to only 2 char
but this is not what i required i need to get if and only 2 digits after hyphen?

Accepted Answer

J. Alex Lee
J. Alex Lee on 8 Mar 2020
out_str = regexp(str, '[A-Z]+-[0-9]{2}$', 'match');


Show 6 older comments
Bhaskar R
Bhaskar R on 12 Mar 2020
Sorry for if i am unclear, need to restrict the input string with specific length as
6 characters-5 digits-2 digits
str = 'ENGINE-12345-23';
In reguler expression
'...-[0-9]{2}$'; % which is restricting the last input after hyphen ( here 23) is ok
% in the same way first two string inputs(ENGINE, 12345) need restrict to 6 and 5 respectively
In the suggested link Anchors working with specfic characters but not with number of characters.
Stephen Cobeldick
Stephen Cobeldick on 12 Mar 2020
@J. Alex Lee: yes thank you, fixed now.
@Bhaskar R: use an anchor. It worked for me:
regexp(str, '^[A-Z]{6}-\d{5}-\d{2}$', 'match', 'once')

Sign in to comment.

More Answers (1)

dpb on 8 Mar 2020
I can get you closer, but not exactly right...
will return only matches of exactly two digits after the "-", but for those cases that do match, also returns the leading "-"
I'm not sure how to prevent that...I'm pretty lame at regular expressions.


Show 4 older comments
J. Alex Lee
J. Alex Lee on 8 Mar 2020
yep, didn't mean to suggest otherwise either.
I don't know relative computational cost either, and hadn't seen comments about it; will definitely keep in mind. But I suppose in any case it makes sense to reach for regex only when you're at the limit of simple text processing.
dpb on 8 Mar 2020
My thinking for past 40 years! I like the quip about only in full agreement! :)
Some people when confronted with a problem think "I know, I'll use regular expressions." Now they have two problems.
Bhaskar R
Bhaskar R on 9 Mar 2020
Thank for the for the response dpb, I have data varying with another string so I had to stick to use only reguler expressions only as of now.

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by