簡體   English   中英

C#在標記/已知單詞之間查找並替換未知單詞

[英]c# find and replace an unknown word between markers/know words

我正在嘗試制作一個程序來替換文件中的單詞,但是當單詞現在是未知單詞時,我不知道如何替換
這是我當文件沒有被修改替換代碼,但是當用戶更改文字/昵稱和想要再次改變它,我需要知道2個字之間的字/昵稱

string path2 = filePath + "\\test\\versions\\"+comboBox1.Text+"\\";
            string text = File.ReadAllText(path2+comboBox1.Text+".json");
            text = text.Replace("${auth_player_name}", textBox1.Text);
            File.WriteAllText(path2+comboBox1.Text+".json", text);

這是詞之間的2個字,我需要更換

--username ${auth_player_name} --version

現在我嘗試未知單詞改為$ {} auth_player_name所以用戶可以再次改變它,這需要那句話,因為我的程序可以編輯相似,但與其他名稱的其他文件

我嘗試了這個但是不工作

text = Regex.Replace(text, "--username \".*\" --ver", "-username \"${auth_player_name}\" --ver");

這是所有的代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace ChangeName
{
    public partial class Form1 : Form
    {
        string filePath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);

        public Form1()
        {
            InitializeComponent();
            DirectoryInfo dinfo = new DirectoryInfo(filePath+"\\.minecraft\\versions");
            FileInfo[] Files = dinfo.GetFiles("*.json", SearchOption.AllDirectories);

            foreach (FileInfo folder in Files)
                comboBox1.Items.Add(Path.GetFileNameWithoutExtension(folder.Name));
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {


            string path2 = filePath + "\\.minecraft\\versions\\"+comboBox1.Text+"\\";
            string text = File.ReadAllText(path2+comboBox1.Text+".json");
            text = text.Replace("${auth_player_name}", textBox1.Text);
            File.WriteAllText(path2+comboBox1.Text+".json", text);

        }


    }
}

正則表達式替換示例

string path2 = filePath + "\\test\\versions\\"+comboBox1.Text+"\\";
string text = File.ReadAllText(path2+comboBox1.Text+".json");
//Changed to Regex
Regex reg = new Regex("--username ([^-]+)--version");
//using regex.replace function
text = reg.Replace(text, "--username " + textBox1.Text + " --version");
//end edit
File.WriteAllText(path2+comboBox1.Text+".json", text);

Regex.Replace的文檔

更新以將文本變量設置為等於替換變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM