Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Capturing a substring

Posted on 2014-11-12
6
Medium Priority
?
132 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:Michael Fowler
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:Michael Fowler
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:
Michael Fowler earned 1000 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Expert Comment

by:Michael Fowler
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 35

Assisted Solution

by:it_saige
it_saige earned 1000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Screencast - Getting to Know the Pipeline

783 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