VB.NET 在引号或其他符号之间获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14927218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:22:30  来源:igfitidea点击:

VB.NET Get text in between Quotations or other symbols

vb.netstring

提问by TheRyan722

I want to be able to extract a string in between quotation marks or parenthesis etc. to a variable. For example my text might be "Hello there "Bob" ". I want to extract the text "Bob" from in between the two quotation marks and put it in the string "name" for later use. The same would be for "Hello there (Bob)". How would I go about this? Thanks.

我希望能够将引号或括号等之间的字符串提取到变量中。例如,我的文字可能是“你好,”鲍勃“”。我想从两个引号之间提取文本“Bob”并将其放入字符串“name”中以备后用。“Hello there (Bob)”也是如此。我该怎么办?谢谢。

=======EDIT======

========编辑======

Sorry, I worded this poorly. Ok, so lets say I have a textbox(Textbox1) and a button. If the user inputs the text: MsgBox "THIS IS MY MESSAGE" I want that when the Button is pressed, only the text THIS IS MY MESSAGE is displayed.

对不起,我措辞不好。好的,假设我有一个文本框(Textbox1)和一个按钮。如果用户输入文本:MsgBox "THIS IS MY MESSAGE" 我希望当按下按钮时,只显示文本这是我的消息。

采纳答案by SysDragon

This is a solution very simple:

这是一个非常简单的解决方案:

Dim sAux() As String = TextBox1.Text.Split(""""c)
Dim sResult As String = ""

If sAux.Length = 3 Then
    sResult = sAux(1)
Else
    ' Error or something (number of quotes <> 2)
End If

回答by jmoreno

There are basically three methods -- regular expressions, string.indexof and substring and finally looping over the characters one by one. I would avoid the latter as it is just reinventing the wheel. Whether to use regexs or indexof depends upon the complexity of your requirements and data. Indexof is a bit wordy but fairly straightforward and possibly just what you want in this case.

基本上有三种方法——正则表达式、string.indexof 和 substring,最后一个一个循环遍历字符。我会避免使用后者,因为它只是在重新发明轮子。是否使用正则表达式或 indexof 取决于您的需求和数据的复杂性。Indexof 有点冗长但相当简单,在这种情况下可能正是您想要的。

Dim str as String = "Hello there ""Bob"""
Dim startName as Integer 
Dim endName as Integer
Dim name as String = ""

startName = str.IndexOf("""")
endName = str.Indexof("""", If(startName > 0, startName,0))
If (endName>startName) Then
    name = str.SubString(startName, endName)
End If

If you need to do this for arbitrary symbols, then you want regexs.

如果您需要对任意符号执行此操作,那么您需要正则表达式。