【问题标题】:Unable to remove unnecessary whitespace before Textbox submission to Database C#在将文本框提交到数据库 C# 之前无法删除不必要的空格
【发布时间】:2019-12-09 15:50:05
【问题描述】:

在将数据提交到数据库之前,我一直在尝试从文本框中删除重复的空格。我在 MySQL 中尝试过 TRIM() 函数,比如

cmd.CommandText = "INSERT INTO table1 VALUES TRIM(('" + textBox1.Text + "', '" + textBox2.Text + "'))";

它没有用。我也试过这个

textBox1.Text = textBox1.Text.Replace("  ", " ");

我在提交按钮中添加了上面的代码,该按钮有效,但只有在出现两次时才会删除空格,例如双倍空格。如果用户输入了两个以上的空格,我该如何实现呢?

例如:"Hello World" 应提交为"Hello World"

【问题讨论】:

  • 使用 Trim() : textBox1.Text = textBox1.Text.Trim();
  • 永远不会从原始用户输入构建可执行字符串。请搜索“SQL注入攻击”了解更多。

标签: c# mysql sql database


【解决方案1】:

试试这个:

stextBox1 = textBox1.Text;

RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
textBox1.Text = regex.Replace(stextBox1 , " ");

得到来自How do I replace multiple spaces with a single space in C#?

您需要添加以下行: using System.Text.RegularExpressions;using System; 下面是一个有效的 c# 示例:

using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string stextBox1 = textBox1.Text;

            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex("[ ]{2,}", options);
            textBox1.Text = regex.Replace(stextBox1, " ");
        }
    }
}

【讨论】:

  • 添加修剪以删除从头到尾的所有空白,只有在中间OP想要折叠多个为一个。
  • 谢谢@zip。这行不通。我有很多错误。刚开始编程,不擅长正则表达式。有什么建议吗?
【解决方案2】:

用正则表达式试试这段代码:

        string str = textBox1.Text;
        str = Regex.Replace(str, @"\s", "");

【讨论】:

  • 你必须保留一个空格字符str = Regex.Replace(str, @"\s+", " ");
【解决方案3】:

这应该是你想要达到的结果:

string str = textBox1.Text;
str = Regex.Replace(str, @"\s+", " ");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    相关资源
    最近更新 更多