How to split a string by specific characters

Hi everyone,
I am having trouble splitting my string which is a path for a document:
MyString = Folder\Test\12345678,12345,Z0123.pdf

I only need the first series of numbers between the “” and “,”. So far, I have the following:
MyString.ToString.Substring(MyString.ToString.LastIndexOf("")+1,8)

I would like to replace the length “8” by a changing parameter based on the “,” as my string does not always have 8 characters. I can also not be sure that there is no other “,” before the one I am looking for.

I hope, this is understandable. Looking very much forward for your help!

MyString.Split("\")(2).Split(",")(0)

2 Likes

@Anthony_Humphries’s answer is the most correct and the one you should use, assuming the format is always the same. If it changes a bit, such as possibly being a longer path, regex might be of use to you (or small edits such as replacing .Split("\")(2) with .Split("\").Last(). Using an explicit index will always be more efficient¹ than Last() but Last() will work regardless of how long the file path is.

  1. The source code for Enumerable.Last reveals the method to be an O(N) operation for anything other than a list (and that too might be O(N), but I’ve not checked). The code iterates through each element in the collection until it hits the last one, then returns that entry.

Thanks a lot to you both! That’s exactly what I needed :slight_smile:
I am not very familiar with regex yet but of what I have seen, that would definitely be an option too. As this is my first actual automation outside the academy trainings, I must say, I am not so much paying attention to efficiency yet as I am just happy when it works. But I will have to take care of that aspect too at some point.
Thanks again and stay healthy!

Hi

We already have a splitter to get the filename from the full path :slight_smile:

Path.GetFileName(myString).Split(","C)(0)

@lena_b

Do you mean in the filename or in the full path?

In the full path. It should definitely be the first in the file name. So your method should work. Does MyString.Split("").Last().Split(",")(0) still work also?

@lena_b

The following should work too (I cannot use a string as split character in my Studio, I always need a character):

MyString.Split("\"C).Last().Split(","C)(0)

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.