2

I've been trying to solve this problem in the last few days with no success. I have the following string:

   comment = '#disabled, Fc = 200Hz'

What I need to do is: if there's the string 'disabled' it needs to be matched. Otherwise I need to match the number that comes before 'Hz'.

The closest solution I found so far was:

  regexpi(comment,'\<#disabled\>|\w*Hz\>','match') ;

It will match the word '#disabled' or anything that comes before 'Hz'. Problem is that when it first finds '#disabled#' it copies also the result '200Hz'.

So I'm getting:

ans = '#disabled' '200Hz'

Summing up, I need to select only the 'disabled' part of a string if there is one, otherwise I need to get the number before 'Hz'.

Can someone give me a hand ?

2
  • you are limited to one line...? Commented Sep 29, 2014 at 9:06
  • No, actually I'm not. Commented Sep 29, 2014 at 9:11

1 Answer 1

5

Suppose your input is:

comment = {'#disabled, Fc = 200Hz';
                      'Fc = 300Hz'}

The regular expression (match disabled if follows # otherwise match digits if they are followed by Hz):

regexp(comment, '(?<=^#)disabled|\d+(?=Hz)','match','once')

Explaining it:

  • ^# - match # at the beginning of the line
  • (?<=expr)disabled - match disabled if follows expr
  • expr1 | expr2 - otherwise match expr2
  • \d+ - match 1 or more digits, equivalently [0-9]+
  • expr(?=Hz) - match expr only if followed by 'Hz'

Diagram:

Regular expression visualization

Debuggex Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Could you explain the matching expression ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.