简体   繁体   中英

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.

I am splitting a string into a string[] with .Split(' ') .
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(' ') .

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? 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"

The key here is that the \\b is the word break metacharacter. So it will match at the beginning or end of a line, and the transitions between word characters (\\w) and non-word characters (\\W). The biggest difference between it and using \\w or \\W is that those won't match at the beginning or end of lines.

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_

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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