Validate and get exact number of characters using the regular expression

조회 수: 20 (최근 30일)
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?
  댓글 수: 1
dpb
dpb 2020년 3월 8일
편집: dpb 2020년 3월 8일
Two exactly, not <=2?
'VCCASNSRR-1' % OK or not?

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

채택된 답변

J. Alex Lee
J. Alex Lee 2020년 3월 8일
Try
out_str = regexp(str, '[A-Z]+-[0-9]{2}$', 'match');
  댓글 수: 9
Stephen23
Stephen23 2020년 3월 12일
편집: Stephen23 2020년 3월 12일
@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')
Bhaskar R
Bhaskar R 2020년 3월 12일
Yes sir, It worked perfectly
Thank you :-)

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

추가 답변 (1개)

dpb
dpb 2020년 3월 8일
I can get you closer, but not exactly right...
regexp(s,'-\d{2}\>','match')
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.
  댓글 수: 7
dpb
dpb 2020년 3월 8일
편집: dpb 2020년 3월 8일
My thinking for past 40 years! I like the quip about only aliens...am 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 2020년 3월 9일
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.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by