【问题标题】:C#: Using regular expression (Regex) to duplicate a specific character in a stringC#:使用正则表达式 (Regex) 复制字符串中的特定字符
【发布时间】:2014-06-05 15:05:20
【问题描述】:

有人知道如何使用正则表达式复制字符串中的特定字符吗?

我有这样输入的路径:

C:/Example/example

我想使用正则表达式(或任何其他方法)来显示它:

C://Example//示例

有可能吗?

这是我获取文件路径的地方

private void btnSearchImage_Click_1(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();

        ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string filenName = ofd.FileName;
            pictureBox1.Image = new Bitmap(filenName);
            string path = filenName;
            txtimgPath.Text = path;

        }


    }

谢谢

【问题讨论】:

  • 你为什么要这样做?对我来说好像XY Problem
  • @tmw 我这样做是因为当我将路径插入到带有单个斜杠的 MySql 数据库中时,它会出于未知原因自动删除该斜杠,但是当我插入另一个斜杠时它会忽略它。不,这是一个不验证解决方案的问题......
  • 你没有明白我的意思。为什么你觉得有必要添加一个额外的/
  • 我刚刚在之前的评论中告诉过你.. 如果我在数据库中正常插入路径,它会显示如下:C:Exampleexample 而不是 C:\Example\example.. 添加另一个斜线将使其正常..
  • 啊哈。你能说明你是如何将它插入数据库的吗?

标签: c# regex character


【解决方案1】:

没有 RegEx 怎么办?

var text = "C:/Example/example";

string outputValue = text.Replace("/","//"); //returns "C://Example//example"

【讨论】:

  • 它不工作。请在我设置字符串路径 = 文件名的行之后查看我正在实施您建议的代码的编辑后的帖子;使用此代码:path.Replace("/", "//");
【解决方案2】:

这应该可行:

private void btnSearchImage_Click_1(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();

    ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 

    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string filenName = ofd.FileName;
        pictureBox1.Image = new Bitmap(filenName);
        string path = filenName.Replace("/", "//");
        txtimgPath.Text = path;

    }


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2015-12-13
    相关资源
    最近更新 更多