Remove text from a text file without otherwise altering the file

I need to remove text from a text file without otherwise altering the file INCLUDING other text in the same line. specifically I need the text of the form 'E\S+' (ie "E3453.464") to go away without otherwise altering the line.
so this: G1 X104.650 Y95.350 E4.58979 should become this G1 X104.650 Y95.350
and this G1 E-2.00000 F2400.00000 should become this G1 F2400.00000

 Accepted Answer

You can use regexprep for this purpose.
x1 = 'G1 X104.650 Y95.350 E4.58979';
x2 = 'G1 E-2.00000 F2400.00000';
x1 = regexprep(x1,'(E-?)([0-9]){0,}\.?(\d+)\s?','');
x2 = regexprep(x2,'(E-?)([0-9]){0,}\.?(\d+)\s?','');
x1 = 'G1 X104.650 Y95.350 '
x2 = 'G1 F2400.00000'
The expression:
  • Match E
  • Match '-' optionally
  • Match numbers 0-9 at least one time
  • Match '.' optionally
  • Match as many digits as possible
  • Match whitespace optionally

6 Comments

Thanks. your version doesn't actually work (I'm not sure why). but thanks for the heads up on using regexprep. I just altered the regex
regexprep(tline,'E\S+\s?','')
output snippet from your version
G92 E0
G1 X95.350 Y95.350 F360.000
G1 F2400.00000
G1 F360
M182;
G1 X104.650 Y95.350 E4.58979
G1 X104.650 Y104.650 E7.17958
G1 X95.350 Y104.650 E9.76937
G1 X95.350 Y95.425 E12.33827
output snippet from my version
G92
G1 X95.350 Y95.350 F360.000
G1 F2400.00000
G1 F360
M182;
G1 X104.650 Y95.350
G1 X104.650 Y104.650
G1 X95.350 Y104.650
G1 X95.350 Y95.425
Didn't not realise E0 could occur, so I changed {1,} to {0,} However the expression I posted matches your conditions:
https://regex101.com/r/BZiZwv/1
Also in your condition you are using \S which will match anything other than a space, tab or newline, rather than matching the individuals characters as I showed. So say there is an entry as:
Etest
ENDING
E?$
Your expression will remove it. Not necessarily important in this situation if you know what the information looks like however its worth noting.
It was the space between the '\s' and the '?' I think. I copy pasted the pre-edited version of yours and that spaced messed it up. It works now.
No worries, glad you fixed it. I have made a very small change in the expression as I forgot to escape the '.'. Should be all good now, please find the updated code in the answer and the updated regex101 link in the comment above.
Note that {0,} is the same as * and {1,} is the same as + in regular expressions. In my opinion, E-{0,} should be E-? (aka E-{0,1})
Totally, the first E-{0,} is actually meant to be E-?, as from the examples OP gave there is only one '-' character. While editing I changed both of them rather than just the second one...

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2016a

Asked:

on 11 Jun 2018

Edited:

on 11 Jun 2018

Community Treasure Hunt

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

Start Hunting!