如何忽略在特定的两个符号内替换文本 [英] How can i ignore replace text within specific two symbol

查看:168
本文介绍了如何忽略在特定的两个符号内替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码片段替换文本

I used following code snippet to replace text

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string A = textBox1.Text.Trim();
        string B = textBox1.Text.Trim();

        A = A.Replace("AB", "CD");
        A = A.Replace("GF", "HI");
        A = A.Replace("AC", "QW");
        A = A.Replace("VB", "GG");

        textBox2.Text = (A);

    }

但我想忽略||作为示例,当我在txtbox1中键入AB GF时,txtbox2替换为以下CD HI,我的代码做这个

but i wants to ignore this replace technique within || these symbol.As a example my code do this


现在我需要当我输入| AB GF |在txtbox1中,txtbox2替换为AB GF

when i type AB GF in a txtbox1,txtbox2 replace as following CD HI. Now i need when i type |AB GF| in txtbox1 ,txtbox2 replace as AB GF

我使用此代码执行此操作

i used this code to do this

textBox2.Text = ((B.Contains("|")) ? B.Replace("|", "") : A);

但这不工作,这个符号都包含txtbox1中的东西,不能替换,我该怎么做

but this isn't work,after | this symbol all containing things in txtbox1 not replaced,how can i do this

推荐答案

根据你的意见,字符串的空格,然后进行替换。之后,你会一起加入。这很容易与Linq。

Per your comments, you will want to split your string on the spaces prior to doing the replacement. Afterwards you will join it all back together. This is pretty easy with Linq.

public Main()
{
    var strings = new string[]{ "AB GF", "|AB| GF" };
    foreach (var s in strings)
        Console.WriteLine(String.Join(" ", s.Split(' ').Select(x => ReplaceText(x))));
}

string ReplaceText(string text)
{
    if (text.Contains("|"))
        return text.Replace("|", String.Empty);
    else
    {
        text = text.Replace("AB", "CD");
        text = text.Replace("GF", "HI");
        text = text.Replace("AC", "QW");
        return text.Replace("VB", "GG");
    }
}

列印:

CD HI

AB HI

查看您的代码。如果你需要避免ReplaceText方法。这样的东西可以工作。

Looking at your code. If you need to avoid a ReplaceText method. Something like this would work.

string A = textBox1.Text.Trim();

var subStrings = A.Split(' ');
for (int i = 0; i < subStrings.Count(); i++)
{
    if (subStrings[i].Contains("|"))
        subStrings[i] = subStrings[i].Replace("|", String.Empty);
    else
    {
        subStrings[i] = subStrings[i].Replace("AB", "CD");
        subStrings[i] = subStrings[i].Replace("GF", "HI");
        subStrings[i] = subStrings[i].Replace("AC", "QW");
        subStrings[i] = subStrings[i].Replace("VB", "GG");
    }
}

textBox2.Text = String.Join(" ", subStrings);

这篇关于如何忽略在特定的两个符号内替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆