Solved

Capturing a substring

Posted on 2014-11-12
6
93 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

896 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now