Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Who can help me with defining a regular expression?

1 回表示 (過去 30 日間)
Henk-Jan Ramaker
Henk-Jan Ramaker 2016 年 9 月 8 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have lines of text that might look like this:
@5%
or
@2.5%
I would like to extract everything between '@' and '%'. The text in between these characters represents a number. Sometimes, the number contains a digit, and sometimes not.
Can anyone help me with a regular expression (so I can use the function regexp) to do so?
Many thanks already.

回答 (1 件)

George
George 2016 年 9 月 8 日
str1 = '@5%';
str2 = '@2.5%';
regex = '\d*\.?\d+';
[s1 e1] = regexp(str1, regex);
[s2 e2] = regexp(str2, regex);
str1(s1:e1)
str2(s2:e2)
>> ans =
5
>> ans =
2.5
Play around with this. The regex captures 0 or more digits, 0 or 1 dots, and one or more digit. It ignores the @ and % signs. There are possibly weird cases where it may not work.
  1 件のコメント
George
George 2016 年 9 月 8 日
Warning, it will match on digits that aren't surrounded by the @ and % signs. If that's important you can modify the regex and adjust the ranges like str1(s1+1:e1-1).

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by