edit part of text in text file using C#

2019-07-23 09:07发布

I'm looking for a way to find a part of text and change the number behind the text using C#

I've made it work in a .batch program but i would like to make it more proper in visual studio.

This is the kind of text file where i need to be able to change the number afther X or/and Y: (with change i mean add a specific number to the number there already us)

N1 G17 G90
N3 G54
N5 S24000
N7 M03
N9 G00 X2675.766 Y427.409 Z730
N11 G00 X2675.766 Y427.409
N13 G00 X2675.766 Y427.409
N15 G00 X2675.766 Y427.409 Z505
N17 F4000
N19 G01 X2675.766 Y427.409 Z447.5
N21 F4000
N23 G01 X2565.966 Y475.823 Z447.5
N25 F4000
N27 G02 X1852.832 Y871.38 Z447.5 I4373.42 J4575.032
N29 G03 X705.065 Y871.38 Z447.5 I1278.948 J28.138
N31 G02 X-8.069 Y475.823 Z447.5 I-1815.523 J4575.032
N33 M05
N35 M30

this is how the batch file works at the moment.

@echo off
setlocal EnableDelayedExpansion
echo[
echo[
set /p file="file name? = "
echo[
echo[
set /p Xdir="X + :"
echo[
echo[
set /p Ydir="Y + :"


(for /F "tokens=1-4*" %%a in (%file%.nc) do (
   if "%%d" equ "" (
      echo %%a %%b %%c
   ) else (
      for /F "tokens=1,2 delims=X." %%C in ("%%c") do (
         set /A X=%%C+%Xdir%
         if "%%D" neq "" set "X=!X!.%%D"
      )
      for /F "tokens=1,2 delims=Y." %%D in ("%%d") do (
         set /A Y=%%D+%Ydir%
         if "%%E" neq "" set "Y=!Y!.%%E"
      )
      echo %%a %%b X!X! Y!Y! %%e
   )
)) > %file%_ar.nc
echo je Your new file " %file%_ar.nc " is created.
pause

in my Visual studio i got : 2 text fields for X and/or Y. named Xdir_btn,Ydir_btn 1 btn called Generate. named Generate_btn 1 richtextBox. named RichTextBox (this is where my text file gets in when i open it). There are enoguh tutorials online to find and replace a specified text, but not about to change something behind a specified text.

标签: c#
1条回答
孤傲高冷的网名
2楼-- · 2019-07-23 09:20

but not about to change something behind a specified text.

Try this regex (?<=X)[0-9\.]+(?= ) It will help you find the number behind X.

N9 G00 X2675.766 Y427.409 Z730

You can try regex101.com. It will clearly explain the code.

查看更多
登录 后发表回答