regex: Extract then delete

36 ビュー (過去 30 日間)
Hau Kit Yong
Hau Kit Yong 2019 年 7 月 4 日
コメント済み: Hau Kit Yong 2019 年 7 月 4 日
Is there a regex function that can extract matched strings and delete them after? I would like to do this without searching over the string twice using regexp(str, expr, 'match') followed by regexprep(str, expr, '').

採用された回答

Stephen23
Stephen23 2019 年 7 月 4 日
編集済み: Stephen23 2019 年 7 月 4 日
"Is there a regex function that can extract matched strings and delete them after?"
Not really.
You could do something like this with regexprep and dynamic expressions to store the matched data in a workspace variable, but this will be slow, complex, and rather fragile.
One simple and efficient workaround would be to use both the match and split outputs: this example matches and removes the digits, leaving only the alphabetic characters:
>> S = 'abcd1234efghi6789jklm';
>> [X,Y] = regexp(S,'\d+','match','split');
>> Z = [Y{:}] % the new string with substrings removed
Z =
abcdefghijklm
>> X{:} % the matched substrings
ans =
1234
ans =
6789
  1 件のコメント
Hau Kit Yong
Hau Kit Yong 2019 年 7 月 4 日
Thank you! This works wonderfully.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by