简体   繁体   English

使用正则表达式替换而不是字符串替换

[英]Using Regex Replace instead of String Replace

I am not clued up on Regex as much as I should be, so this may seem like a silly question. 我对Regex的了解不如预期,所以这似乎是一个愚蠢的问题。

I am splitting a string into a string[] with .Split(' ') . 我正在使用.Split(' ')string拆分为string[]
The purpose is to check the words, or replace any. 目的是检查单词或替换任何单词。

The problem I'm having now, is that for the word to be replaces, it has to be an exact match , but with the way I'm splitting it, there might be a ( or [ with the split word. 我现在遇到的问题是,要替换的单词必须完全匹配 ,但是按照我拆分的方式,可能会有([包含拆分单词。

So far, to counter that, I'm using something like this: 到目前为止,为了解决这个问题,我正在使用类似这样的方法:
formattedText.Replace(">", "> ").Replace("<", " <").Split(' ') . formattedText.Replace(">", "> ").Replace("<", " <").Split(' ')

This works fine for now, but I want to incorporate more special chars, such as [;\\\\/:*?\\"<>|&'] . 目前,这可以正常工作,但是我想合并更多特殊字符,例如[;\\\\/:*?\\"<>|&']

Is there a quicker way than the method of my replacing, such as Regex? 有没有比我的替换方法(例如Regex)更快的方法? I have a feeling my route is far from the best answer. 我觉得我的路线远未达到最佳答案。

EDIT 编辑
This is an (example) string
would be replaced to 将被替换为
This is an ( example ) string

If you want to replace whole words, you can do that with a regular expression like this. 如果要替换整个单词,可以使用这样的正则表达式来实现。

string text = "This is an example (example) noexample";
string newText = Regex.Replace(text, @"\bexample\b", "!foo!");

newText will contain "This an !foo! (!foo!) noexample" newText将包含"This an !foo! (!foo!) noexample"

The key here is that the \\b is the word break metacharacter. 这里的关键是\\b是单词break元字符。 So it will match at the beginning or end of a line, and the transitions between word characters (\\w) and non-word characters (\\W). 因此它将在行的开头或结尾以及单词字符(\\ w)和非单词字符(\\ W)之间的过渡处匹配。 The biggest difference between it and using \\w or \\W is that those won't match at the beginning or end of lines. 它与使用\\ w或\\ W的最大区别在于,它们在行的开头或结尾不匹配。

I thing this is the right thing you want 我觉得这是你想要的正确的事情

if you want these -> ;\\/:*?"<>|&' symbols to replace 如果要用这些->; \\ /:*?“ <> |&'符号代替

string input = "(exam;\\/:*?\"<>|&'ple)";
        Regex reg = new Regex("[;\\/:*?\"<>|&']");
        string result = reg.Replace(input, delegate(Match m)
        {
            return " " + m.Value + " ";
        });

if you want to replace all characters except a-zA-Z0-9_ 如果要替换除a-zA-Z0-9_以外的所有字符

 string input = "(example)";
        Regex reg = new Regex(@"\W");
        string result = reg.Replace(input, delegate(Match m)
        {
            return " " + m.Value + " ";
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM