C# 无法在文本框提交到数据库C之前删除不必要的空白#
在将数据提交到数据库之前,我一直在尝试从文本框中删除重复的空白。我在MySQL中尝试了C# 无法在文本框提交到数据库C之前删除不必要的空白#,c#,mysql,sql,database,C#,Mysql,Sql,Database,在将数据提交到数据库之前,我一直在尝试从文本框中删除重复的空白。我在MySQL中尝试了TRIM()函数,比如 cmd.CommandText = "INSERT INTO table1 VALUES TRIM(('" + textBox1.Text + "', '" + textBox2.Text + "'))"; 它不起作用。我也试过这个 textBox1.Text = textBox1.Text.Replace(" ", " "); 我将上面的代码添加到submission按钮中,该按
TRIM()
函数,比如
cmd.CommandText = "INSERT INTO table1 VALUES TRIM(('" + textBox1.Text + "', '" + textBox2.Text + "'))";
它不起作用。我也试过这个
textBox1.Text = textBox1.Text.Replace(" ", " ");
我将上面的代码添加到submission按钮中,该按钮可以工作,但只有当它出现两次时,它才会删除空白,就像在双空格中一样。在用户输入两个以上空格的情况下,如何实现它
例如:“Hello World”
应作为“Hello World”
提交,请尝试以下操作:
stextBox1 = textBox1.Text;
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
textBox1.Text = regex.Replace(stextBox1 , " ");
得到的是来自
您需要添加以下行:
使用System.Text.regular表达式使用系统下的code>代码>
下面是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, " ");
}
}
}
使用正则表达式尝试以下代码:
string str = textBox1.Text;
str = Regex.Replace(str, @"\s", "");
这应该是您想要实现的结果:
string str = textBox1.Text;
str = Regex.Replace(str, @"\s+", " ");
使用Trim():textBox1.Text=textBox1.Text.Trim();永远不要从原始用户输入构建可执行字符串。请搜索“SQL注入攻击”,以了解更多。添加修剪,以消除所有空白,从开始和结束,它只是在中间的OP要崩溃多对一。谢谢@ zip。这不管用。我犯了很多错误。刚开始编程,不擅长正则表达式。有什么提示吗?你必须保留一个空格charstr=Regex.Replace(str,@“\s+”,“”)代码>