从文本框中的给定字符串中提取子字符串 [英] Extracting a substring from a given string in textbox
本文介绍了从文本框中的给定字符串中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,
我想从用户在C#中输入文本框的字符串中提取子字符串。我需要的子串将在输入的字符串之间。
例如,如果用户输入select asd,fkdl from table,
,
我需要asd,fkdl作为我的子串。
我该怎么做请帮助。
我尝试了什么:
Hello,
I want to extract a substring from a string which the user enters into the textbox in C#. The substring I need would be in between the string entered.
For example,
if the user enters "select asd,fkdl from table",
I need "asd,fkdl" as my substring.
How do I do that Please help.
What I have tried:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string x = (sender as Control).Text;
string temp;
listBox1.BeginUpdate();
string str = textBox1.Text.ToString();
int p = str.IndexOf(' ');
int len = str.Length;
try
{
for (int i = 8; str[i] != ' '; i++)
{
var substr = str.Substring(8,i+1);
temp = substr;
MessageBox.Show(temp,"Substring");
}
}
finally
{
listBox1.EndUpdate();
}
推荐答案
现在是时候了解正则表达式 [ ^ ]。
It is time to learn about Regular Expressions[^].
使用正则表达式:
Use a regex:
string input = "select asd,fkdl from table";
Match m = Regex.Match(input, @"(?<=select\s+).+?(?=\s+from)", RegexOptions.IgnoreCase);
if (m.Success)
{
string substr = m.Value;
}
,不使用正则表达式
without using Regex
string input = "select asd,fkdl from table";
int start = input.IndexOf("select")+6;
var columns = input.Substring(start, input.IndexOf("from") - start).Trim(); //"asd,fkdl"
这篇关于从文本框中的给定字符串中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文