Validate and get exact number of characters using the regular expression
Mostra commenti meno recenti
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 Commento
Two exactly, not <=2?
'VCCASNSRR-1' % OK or not?
Risposta accettata
Più risposte (1)
dpb
il 8 Mar 2020
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 Commenti
J. Alex Lee
il 8 Mar 2020
maybe I misunderstood the requirements. Do you need just the digits, or also the string and hyphen preceding?
candidates = [...
"SOMETHING-2",...
"ENGINE-45",...
"ACCCAT-455",...
"VCCASNSRR-12344"]
origmatches = regexp(candidates, '[A-Z]+-[0-9]{2}', 'match')
fullmatches = regexp(candidates, '[A-Z]+-[0-9]{2}$', 'match')
numericmatches = regexp(candidates,'-\d{2}\>','match')
If you want something like the last, and don't want the hyphen, i think you could use some lookbehind
Hmmm...rereading I see where you're coming from...looks like maybe he is trying to extract the strings+digits but only those with two digits after the hyphen. For that I'd probably just use a count if it is exactly two and forget the overhead of regexp entirely.
>> candidates(strlength(extractAfter(candidates,'-'))==2)
ans =
"ENGINE-45"
>>
J. Alex Lee
il 8 Mar 2020
nice solution, but still assumes what I assumed with regex, that the numbers are terminal
dpb
il 8 Mar 2020
Oh, no claims it's anything other than the same thing; just don't need to figure out regex that way... :)
I've seen comments that regex is also fairly expensive; how it would compare on large array I've no idea, didn't test.
J. Alex Lee
il 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.
Bhaskar R
il 9 Mar 2020
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!