如何替换正则表达式中的用户输入? [英] How to replace a user input in regular expression?

查看:44
本文介绍了如何替换正则表达式中的用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会用简单的代码来描述我的情况.例如,这里是代码:

I will use simple codes to describe my situation. For example, here are the codes:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(?!non)\w+\b";
      string input = "Nonsense is not always non-functional.";
      foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
         Console.WriteLine(match.Value);
   }
}

现在,我想用用户输入替换非".假设它被称为用户输入",并且代码是为获取用户输入而完美编写的.我想这样做,但存在错误:

Now, I would like to replace the "non" with a user input. Let say it's called "UserInput" and the codes are written perfectly for getting the user input. I want to do like this, but error exists:

string pattern = @"\b(?!{0})\w+\b", UserInput;

有没有办法用用户输入替换正则表达式模式中的非"?

Is there any way to replace the "non" inside the pattern of regex with user input?

推荐答案

我认为你只是缺少 string.Format():

string pattern = string.Format(@"\b(?!{0})\w+\b", UserInput);

这篇关于如何替换正则表达式中的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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