Solved

Capturing a substring

Posted on 2014-11-12
6
103 Views
Last Modified: 2014-11-13
This should be a very easy question (I just don't know it).  Usually I grab a substring from a larger string using string.substring(start position, length to capture).  I want to know if there is a way to do something like start position, stop position.  
For example:
Dim str as  string ="something to [remember] for all time."
Dim NewStr as String = str.substring(indexof("["), indexof("]"))
The result being NewStr would equal "[remember]".

This would save me from doing the following:
Dim str as  string ="something to [remember] for all time."
Dim NewStr as String = str.substring(str.indexof("["), str.indexof("]")-str.indexof("]")+1)
0
Comment
Question by:NevSoFly
  • 4
6 Comments
 
LVL 23

Expert Comment

by:Michael74
ID: 40439173
I think you are after the Mid function
http://msdn.microsoft.com/en-us/library/05e63829(v=vs.90).aspx

Michael
0
 
LVL 23

Expert Comment

by:Michael74
ID: 40439174
Here are some examples

' Creates text string. 
Dim TestString As String = "Mid Function Demo" 
' Returns "Mid". 
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo". 
Dim LastWord As String = Mid(TestString, 14, 4)
' Returns "Function Demo". 
Dim MidWords As String = Mid(TestString, 5)

Open in new window

0
 
LVL 23

Accepted Solution

by:
Michael74 earned 250 total points
ID: 40439185
Sorry I thought this through after posting and realized that this is not going to help, in fact it is the depreciated version of the same function. Looking at
http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx
It does not appear that there is a function that does this but you could always use regex match to achieve the same results
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 23

Expert Comment

by:Michael74
ID: 40439196
Imports System.Text.RegularExpressions

Dim text As String = "something to [remember] for all time."
Dim regex As Regex = New Regex("\[.*\]")
Dim NewStr as String =regex.Match(text).Value

Open in new window

http://www.dotnetperls.com/regex-match-vbnet
0
 
LVL 33

Assisted Solution

by:it_saige
it_saige earned 250 total points
ID: 40439229
When you start sub-stringing in this way, you have to remember that the length value is the length of the resulting string.  So in your case, you want to start at the first [ and then end at the second ], which is nine characters away.

So your resulting substring request would look something like this:
Dim NewStr As String = str.Substring(str.IndexOf("["), ((str.IndexOf("]") + 1) - str.IndexOf("[")))

Open in new window

Lovely looking isn't she?  

Honestly, not really.  You start combining a few of those together and you will, literally, get a headache.

So here are a couple of different options and they are based on what you are looking for in this case.

1. Build an extension method that takes a string, start character and end character that produces a substring result

Module Extensions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As Char, ByVal endChar As Char) As String
		Return data.Partialstring(New String() {startChar.ToString(), endChar.ToString()})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As Char, ByVal endChar As String) As String
		Return data.Partialstring(New String() {startChar.ToString(), endChar})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As String, ByVal endChar As Char) As String
		Return data.Partialstring(New String() {startChar, endChar.ToString()})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As String, ByVal endChar As String) As String
		Return data.Partialstring(New String() {startChar, endChar})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal matches As Char()) As String
		Dim result As String = String.Empty
		If matches.Count Mod 2 = 0 Then
			result += data.Partialstring(New String() {matches(0).ToString(), matches(1).ToString()})
		End If
		Return result
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal matches As String()) As String
		Dim result As String = String.Empty
		If matches.Count Mod 2 = 0 Then
			result = data.Substring(data.IndexOf(matches(0)), ((data.IndexOf(matches(1)) + 1) - data.IndexOf(matches(0))))
		End If
		Return result
	End Function
End Module

Open in new window

2. Use a regular expression (as suggested by Michael74)

Dim regx = New Regex(".*?" + "(\[.*?\])", RegexOptions.IgnoreCase Or RegexOptions.Singleline)
Dim matchs = regx.Match(str)
If (matchs.Success) Then
	Dim match = matchs.Groups(1)
	Console.WriteLine(String.Format("{0}", match))
End If

Open in new window


Full Program -
Imports System.Text.RegularExpressions

Module Module1
	Sub Main()
		Dim str As String = "something to [remember] for all time."
		Dim NewStr As String = str.Substring(str.IndexOf("["), ((str.IndexOf("]") + 1) - str.IndexOf("[")))
		Console.WriteLine(NewStr)
		Console.WriteLine(str.Partialstring("[", "]"))

		Dim regx = New Regex(".*?" + "(\[.*?\])", RegexOptions.IgnoreCase Or RegexOptions.Singleline)
		Dim matchs = regx.Match(str)
		If (matchs.Success) Then
			Dim match = matchs.Groups(1)
			Console.WriteLine(String.Format("{0}", match))
		End If

		Console.ReadLine()
	End Sub
End Module

Module Extensions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As Char, ByVal endChar As Char) As String
		Return data.Partialstring(New String() {startChar.ToString(), endChar.ToString()})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As Char, ByVal endChar As String) As String
		Return data.Partialstring(New String() {startChar.ToString(), endChar})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As String, ByVal endChar As Char) As String
		Return data.Partialstring(New String() {startChar, endChar.ToString()})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal startChar As String, ByVal endChar As String) As String
		Return data.Partialstring(New String() {startChar, endChar})
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal matches As Char()) As String
		Dim result As String = String.Empty
		If matches.Count Mod 2 = 0 Then
			result += data.Partialstring(New String() {matches(0).ToString(), matches(1).ToString()})
		End If
		Return result
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function Partialstring(ByVal data As String, ByVal matches As String()) As String
		Dim result As String = String.Empty
		If matches.Count Mod 2 = 0 Then
			result = data.Substring(data.IndexOf(matches(0)), ((data.IndexOf(matches(1)) + 1) - data.IndexOf(matches(0))))
		End If
		Return result
	End Function
End Module

Open in new window


Produces the following output:Capture.JPG
And mind you with the extensibility of .NET, this is just a small sample of examples using a few varying methods.  There are many, many, many other solutions available, some even that use LINQ.

-saige-
0
 

Author Closing Comment

by:NevSoFly
ID: 40441890
Thanks guys. So basically there isn't a built-in way of doing this in .net but I could create an extension method if I really wanted to.  It is nice to know in case I ever find myself in need.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question