2

I have the following string in MATLAB, for example

@#%%F1_USA(40)_u

and I want

F1_USA_40__u

Does it has any function for this?

2
  • What exactly do you want? Strip all the non-alphanumeric characters, except the parentheses which should be replaced by underscores instead? Commented Apr 28, 2011 at 9:48
  • From the beginning of the word I want to remove the non-alphanumeric characters and in the words I want to replace with '_' Commented Apr 28, 2011 at 9:50

2 Answers 2

2

Your best bet is probably regexprep which allows you to replace parts of a string using regular expressions:

s_new = regexprep(regexprep(s, '[()]', '_'), '[^A-Za-z0-9_]', '')

Update: based on your updated comment, this is probably what you want:

s_new = regexprep(regexprep(s, '^[^A-Za-z0-9_]*', ''), '[^A-Za-z0-9_]', '')

or:

s_new = regexprep(regexprep(s, '[^A-Za-z0-9_]', '_'), '^_*', '')
Sign up to request clarification or add additional context in comments.

2 Comments

There is a typo in the first solution of your update. You should have a '_' instead of a '' at the end. Also, using cell array inputs for the expressions and replacement strings will allow you to make just one call to REGEXPREP.
The first solution refers to the stage when it was unclear what the OP wanted - I have assumed that he wants to replace parentheses with underscores and then strip everything that is not alphanumeric or an underscore. Also, thanks for the link, I didn't know about that. Very useful!
1

One way to do this is to use the function ISSTRPROP to find the indices of alphanumeric characters and replace or remove the others accordingly:

>> str = '@#%%F1_USA(40)_u';           %# Sample string
>> index = isstrprop(str,'alphanum');  %# Find indices of alphanumeric characters
>> str(~index) = '_';                  %# Set non-alphanumeric characters to '_'
>> str = str(find(index,1):end)        %# Remove any leading '_'

str =

F1_USA_40__u                           %# Result

If you want to use regular expressions (which can get a little more complicated) then the last suggestion from Tamas will work. However, it can be greatly simplified to the following:

str = regexprep(str,{'\W','^_*'},{'_',''});

Comments

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.