find string pattern in strings ( 'ab*d' in 'abcd')

12 ビュー (過去 30 日間)
Jannis Maq
Jannis Maq 2016 年 6 月 2 日
コメント済み: Jannis Maq 2016 年 6 月 3 日
Hello,
I want to check if there is a string pattern within a string. The pattern may look like this: 'ab*d', where * could be one or more charakters or none. So if the pattern would be 'abQWEd' or 'abd' I still want to have a positive feedback. Do you know how to do this?
Thanks!

採用された回答

Elias Gule
Elias Gule 2016 年 6 月 2 日
try this:
pattern = 'ab.*d'; %%Pattern to match
textstr = 'sqthabVUYd'; %%Input string
match = regexp(textstr,pattern,'match');
this will match 'abVUYd' in the input string.
  2 件のコメント
Jannis Maq
Jannis Maq 2016 年 6 月 2 日
Perfect, exactly what I was looking for! Thank you very much.
Jannis Maq
Jannis Maq 2016 年 6 月 2 日
Ah, I was too fast. Is there a way to make ".*" not include all charakters? If there is a "n" or a "N" it shall not work. Do you also know how to solve this?

サインインしてコメントする。

その他の回答 (1 件)

Elias Gule
Elias Gule 2016 年 6 月 3 日
編集済み: Elias Gule 2016 年 6 月 3 日
I presume that you want it to work for all patterns 'ab.*d' that don't contain the letter "n" or "N", such that "abCDnMMd" does not produce a valid match while "abCDMMdn" does. If that's the case then, try this pattern:
pattern = 'ab((\W*[a-mA-Mo-zO-Z0-9]*\W*)*)d'; %%Pattern to match
*Note:
\W* => zero or more non-word characters
[a-mA-Mo-zO-Z]* => a group of zero or more upper or lowercase letters of the alphabet excluding "n" or "N".
  1 件のコメント
Jannis Maq
Jannis Maq 2016 年 6 月 3 日
Thanks for your reply. Your presumption is right!
But the code doesn't work exactly how I want.
test='((\W*[a-mA-Mo-zO-Z0-9]*\W*)*)6';
regexp(test,'n6','match')
ans =
{} %%Expected answer
regexp(test,'6','match')
ans =
'6' %%Expected answer
regexp(test,'ABC6','match')
ans =
{} %%Not expected :(
But when I put the inputs this way
regexp('ABC6',test,'match')
ans =
'ABC6' %Expected answer
%%But then the problem is:
regexp('n6',test,'match')
ans =
'6' % Not expected, because of the 'n'

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by