在字符串中找到一个词 [英] finding a word in a string
问题描述
大家好,
我正在制作另一种编程语言,而这种编程语言的不同之处在于您可以使用自己的名称来创建变量.我以前的代码,要设置一个变量,您将必须输入类似于以下内容的代码:
string1 =某物
打印字符串1
在我的新语言中,我想像这样编写代码:
#x:Hello World
print_var x
但是我要执行此操作的方式不是创建新变量,而是要查找变量名.我希望源代码看起来像这样:
hey guys,
i am making another programming language and the difference in this one is that you can make a variable with its own name. my previous ones, to set a variable, you would have to type a piece of code similar to:
string1 = something
print string1
in my new language, i want to make that code like this:
#x: Hello World
print_var x
but the way that i want to do this, is not making a new variable, i want to make it finding the variable name. i want the source code to look something like this:
for each a as string in textbox1.text.split(system.environment.newline())
if a.contains("print_var ")
variable = a.findstring(a.substring(10))
textbox2.text = textbox2.text & vbcrlf & variable
end if
next
could you please give me a piece of code that look similar to this ^ but can find the word?
推荐答案
以下代码可用于提取变量的值:来自TextBox1
的Text
.由于变量名称是使用a.SubString(10)
从Index 10
获取的 最好使用a.StartsWith
方法而不是a.contains
方法.
The following code can be used to extract the value of variable fromText
ofTextBox1
. Since, the variable name is taken fromIndex 10
usinga.SubString(10)
it is better to usea.StartsWith
method instead ofa.contains
method.
For Each a As String In TextBox1.Text.Split(ControlChars.Lf)
If a.StartsWith("print_var ") Then
TextBox2.Text &= vbCrLf + System.Text.RegularExpressions.Regex.Match( _
TextBox1.Text, String.Format("(?<=#{0}: ).*", a.Substring(10)), _
RegexOptions.CultureInvariant).Value
End If
Next
(?<=#{0}: )
模式与#x:
匹配,但将其从Match.Value
中排除.
按此解决方案的注释中的要求添加了C#代码[/编辑]
请尝试以下代码:
The (?<=#{0}: )
pattern matches #x:
, but excludes it from the Match.Value
.
C# code added as sought in the comment to this solution [/Edit]
Please try the following code:
foreach (string a in TextBox1.Text.Split('\n')) {
if (a.StartsWith("print_var ")) {
TextBox2.Text += "\r\n" + System.Text.RegularExpressions.Regex.Match(TextBox1.Text, string.Format("(?<=#{0}: ).*", a.Substring(10)), RegexOptions.CultureInvariant).Value;
}
}
如果要在TextBox2
的开头避免使用enter (new line)
,则将TextBox2.Text
初始化为String.Empty
并有条件地引入vbCrLf
,如图所示在下面.
If theenter (new line)
is to be avoided in the beginning ofTextBox2
, then initializeTextBox2.Text
toString.Empty
and introducevbCrLf
conditionally as shown below.
TextBox2.Text = String.Empty
For Each a As String In TextBox1.Text.Split(ControlChars.Lf)
If a.StartsWith("print_var ") Then
TextBox2.Text &= iif(String.IsNullOrEmpty(TextBox2.Text), _
String.Empty, vbCrLf) & System.Text.RegularExpressions.Regex.Match( _
TextBox1.Text, String.Format("(?<=#{0}: ).*", a.Substring(10)), _
RegexOptions.CultureInvariant).Value
End If
Next
这篇关于在字符串中找到一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!