Solved

Capturing a substring

Posted on 2014-11-12
6
106 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
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 34

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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

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.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

752 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