Solved

Capturing a substring

Posted on 2014-11-12
6
89 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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 32

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

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.
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…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

757 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

18 Experts available now in Live!

Get 1:1 Help Now