regexp pattern for only allowing numbers at the end of a string?

7 次查看(过去 30 天)
I have a cell array of strings and need to figure out which strings match a certain pattern.
Rules for when the pattern should match
1. The string contains integers separated by '-'
2. The string has to start with '2' or '3'
3. The string has to end with '6'
4. The string has to end with an arbitrary repetition of '-5' (including 0 times)
5. After the first occurence of '-5' no other numbers except the final 6 (see rule 3) are allowed (e.g. not allowed: 3-1-5-1-5-6)
Examples where the regexp pattern should match:
3-5-5-5-5-6
3-6
3-1-2-1-2-2-5-5-5-6
3-1-2-5-6
Examples where the regexp pattern should not match:
3-1-5-1-5-6
3-1-5-1-5-5-5-6
My question: Which regexp pattern realizes rules 1-4?
I've already managed to find a regext pattern that checks against rules 1-4 in the list above. However, I don't know how to add rule 5 to the pattern:
% Create patternDirectRays = a regexp pattern for the direct rays
% Example: The regexp pattern <pattern> for start numbers 2 and 3, last-but-one-numbers 5 and last number 6 is
% pattern = '^(2|3)(-5)*(-6)$' => ^(2|3) means 'has to start with 2 or 3' / (-5)* means ...followed by 0,1 or more repetitions of '-5' / (-6) = ..and finishes with '-6'
% The following strings would match <pattern>:
% regexp('3-5-5-6', '^(2|3)(-5)*(-6)$', 'match') => '3-5-5-6'
% regexp('2-5-5-6', '^(2|3)(-5)*(-6)$', 'match') => '3-5-5-6'
% regexp('3-5-5-5-5-6', '^(2|3)(-5)*(-6)$', 'match') => '3-5-5-5-5-6'
% regexp('3-6', '^(2|3)(-5)*(-6)$', 'match') => '3-6'
myPattern = '^(2|3)(-5)*(-6)$'
% Get indices of matching strings
idx = regexp(rayPaths, myPattern, 'start');

回答(1 个)

Anushka
Anushka 2025-1-31
Hello @Wolf,
To include Rule 5 in your regular expression pattern, you need to ensure that after the first occurrence of -5, no other numbers except the final -6 are allowed. Follow the below mentioned steps to construct the pattern :
1. Start with 2 or 3.
2. Allow any sequence of numbers and dashes, but after the first occurence of -5 , only -5 or -6 can follow.
3. Ensure the string ends with -6.
Here's the updated regular expression pattern:
myPattern = '^(2|3)(-[0-9]+)*(-5)*-6$';
For applying the pattern, 'regexp' function can be utilized.
Refer to the below mentioned MATLAB Documentation link for the ‘regexp’ function:
Hope this helps.

类别

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