gpt4 book ai didi

character - 替换C#中的字符

转载 作者:行者123 更新时间:2023-12-01 11:40:15 25 4
gpt4 key购买 nike

我有一个要求。

我有一个可以包含任何字符的文本。

a) 我必须只保留字母数字字符b) 如果发现单词“The”的前缀或后缀有空格,则需要将其删除。

例如

CASE 1:

Input: The Company Pvt Ltd.

Output: Company Pvt Ltd

But

Input: TheCompany Pvt Ltd.

Output: TheCompany Pvt Ltd

because there is no space between The & Company words.

CASE 2:

Similarly, Input: Company Pvt Ltd. The

Output: Company Pvt Ltd

But Input: Company Pvt Ltd.The

Output: Company Pvt Ltd

Case 3:

Input: Company@234 Pvt; Ltd.

Output: Company234 Pvt Ltd

No , or . or any other special characters.

我基本上是将数据设置为一些变量,例如

 _company.ShortName = _company.CompanyName.ToUpper();

所以在保存的时候我什么也做不了。只有当我从数据库中获取数据时,我才需要应用此过滤器。数据来自 _company.CompanyName

我必须对其应用过滤器。

到此为止

public string ReplaceCharacters(string words)
{
words = words.Replace(",", " ");
words = words.Replace(";", " ");
words = words.Replace(".", " ");
words = words.Replace("THE ", " ");
words = words.Replace(" THE", " ");
return words;
}

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(ReplaceCharacters(textBox1.Text.ToUpper()));
}

提前致谢。我正在使用 C#

最佳答案

这是一个与您提供的案例相匹配的基本正则表达式。需要注意的是,正如 Kobi 所说,您提供的案例不一致,所以我从前四个测试中去掉了时间段。如果两者都需要,请添加评论。

这可以处理您需要的所有情况,但边缘情况的迅速扩散让我觉得也许您应该重新考虑最初的问题?

    [TestMethod]
public void RegexTest()
{
Assert.AreEqual("Company Pvt Ltd", RegexMethod("The Company Pvt Ltd"));
Assert.AreEqual("TheCompany Pvt Ltd", RegexMethod("TheCompany Pvt Ltd"));
Assert.AreEqual("Company Pvt Ltd", RegexMethod("Company Pvt Ltd. The"));
Assert.AreEqual("Company Pvt LtdThe", RegexMethod("Company Pvt Ltd.The"));
Assert.AreEqual("Company234 Pvt Ltd", RegexMethod("Company@234 Pvt; Ltd."));
// Two new tests for new requirements
Assert.AreEqual("CompanyThe Ltd", RegexMethod("CompanyThe Ltd."));
Assert.AreEqual("theasdasdatheapple", RegexMethod("the theasdasdathe the the the ....apple,,,, the"));
// And the case where you have THETHE at the start
Assert.AreEqual("CCC", RegexMethod("THETHE CCC"));
}

public string RegexMethod(string input)
{
// Old method before new requirement
//return Regex.Replace(input, @"The | The|[^A-Z0-9\s]", string.Empty, RegexOptions.IgnoreCase);
// New method that anchors the first the
//return Regex.Replace(input, @"^The | The|[^A-Z0-9\s]", string.Empty, RegexOptions.IgnoreCase);
// And a third method that does look behind and ahead for the last test
return Regex.Replace(input, @"^(The)+\s|\s(?<![A-Z0-9])[\s]*The[\s]*(?![A-Z0-9])| The$|[^A-Z0-9\s]", string.Empty, RegexOptions.IgnoreCase);
}

我还在我的示例中添加了一个测试方法,该方法使用包含正则表达式的 RegexMethod。要在您的代码中使用它,您只需要第二种方法。

关于character - 替换C#中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1699240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com