|
-
Feb 19th, 2024, 10:54 AM
#1
Thread Starter
Frenzied Member
Getting a string within a string
What's the easiest way to get the string between the parentheses in the following string:
Code:
RPM|Cabinet - Tall - -Notch (18.000H x 1.500W) - Black - Edge: Black
In this example the returned string should be "18.000H x 1.500W". The parts inside & outside the parentheses can be different each time & different lengths.
I would think you could do this with regex, but I couldn't get it to work. Thanks...
-
Feb 19th, 2024, 11:00 AM
#2
Re: Getting a string within a string
Yes, you should be able to do this with RegEx, and yes, RegEx can be a pain to learn. But there may be easier ways.
1) Are there only one pair of parentheses? If so, then InStr can get both the opening and the closing locations. String.Substring can get what is between those two points.
2) If what is between the parentheses is always EXACTLY the same length (which seems a bit unlikely, as the left side of the decimals seem likely to vary between at least one and two characters), then you only need to get the opening parenthesis, which InStr can do.
My usual boring signature: Nothing
 
-
Feb 19th, 2024, 11:11 AM
#3
Thread Starter
Frenzied Member
Re: Getting a string within a string
Yes, should only ever be 1 pair of parentheses & the part between the parentheses may not always be the same length.
After playing around a bit I came up with this as a working solution. I'm sure there are better ways to do it though...
Code:
Dim subStr as String = myString.Split("("c)(1).Split(")"c)(0)
-
Feb 19th, 2024, 11:13 AM
#4
Re: Getting a string within a string
Will the bit you want always be between brackets (braces)? If so, I would just do this:
Code:
Dim TestData As String = "RPM|Cabinet - Tall - -Notch (18.000H x 1.500W) - Black - Edge: Black"
Dim iOpen As Integer = TestData.IndexOf(CChar("("))
Dim iClose As Integer = TestData.IndexOf(CChar(")"))
Dim result As String = TestData.Substring(iOpen + 1, iClose - iOpen - 1)
-
Feb 19th, 2024, 12:58 PM
#5
Re: Getting a string within a string
There are multiple ways to skin this cat. You split example would work, paulg4ije's substring example would work, but if you wanted a RegEx solution then you can use:
Code:
Public Function GetValueInsideParentheses(input As String) As String
Dim pattern = "\(([^)]*)\)"
Dim match = Regex.Match(input, pattern)
Dim value = String.Empty
If (match.Success) Then
value = match.Groups(1).Value
End If
Return value
End Function
Fiddle: https://dotnetfiddle.net/hL7n34
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|