Regular expressions: dealing with spaces

30 ビュー (過去 30 日間)
pietro
pietro 2016 年 5 月 3 日
編集済み: Stephen23 2021 年 4 月 21 日
Hi all,
I have different strings wich they differ from the number of spaces among words. I need to find a way to find this string pattern in a long string.
For example
TxT='f 2000 min';
TxT='f2000min';
TxT='f 2000 min';
At first, I came up with this,
regexp(Txt,'(f \d+ min)||(of\d+min)','match')
but it doesn't work for the last case for the number of spaces. Is there any way to not consider spaces into regular expressions or that a variable number of spaces inside the string might be in the strings?
  2 件のコメント
Guillaume
Guillaume 2016 年 5 月 3 日
Note that OR in regular expressions is a single bar |, your regular expression would theoretically match an empty string (it doesn't because the regular expression engine never matches empty)
See Stephen's answer for the solution. Do not use | when you only need to change the number of times a character needs to be match. It will usually be slower than just using quantifiers (*, ?, +, {m, n}, {m,}, or {n})
pietro
pietro 2016 年 5 月 3 日
Thank you so much.

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

採用された回答

Stephen23
Stephen23 2016 年 5 月 3 日
編集済み: Stephen23 2021 年 4 月 21 日
You were almost there:
>> fmt = 'f *\d+ *min';
>> regexp('f 2000 min',fmt,'match')
ans =
f 2000 min
>> regexp('f2000min',fmt,'match')
ans =
f2000min
>> regexp('f 2000 min',fmt,'match')
ans =
f 2000 min
One of the best things about MATLAB is the great documentation. It means that you don't have to guess how MATLAB works, or ask random strangers on internet forums. The documentation is online, and searchable using your favorite internet search engine. And when I searched for ˇMATLAB regular expression", this is the first result:
It explains how to specify how many times characters or patterns should be matched.
  2 件のコメント
pietro
pietro 2016 年 5 月 3 日
Thank you so much.
Jan
Jan 2017 年 10 月 25 日
編集済み: Jan 2021 年 4 月 21 日
I have removed the flag. Stephen's answer contains a solution and is polite. It is not ironic to suggest to use the documentation, but useful.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by