0

I want to extract a substring from a string based on the delimiter /. The substring extraction has to be hungry so the I want to get all characters from the string up to the last /. Example:

String: /ab/bcd/casd/adsd/se/23

Substring: /ab/bcd/casd/adsd/se/

P.S.: I have seen other QnAs and they don't answer the specific part where the last delimiter occurrence should be used to extract the substring.

1 Answer 1

2
@ECHO OFF
SETLOCAL
SET "String=/ab/bcd/casd/adsd/se/23"
FOR /f "delims=" %%a IN ("%string%") DO SET substring=%%~pa
SET "substring=%substring:\=/%"
echo %substring%

GOTO :EOF

You're a little short on specifics. This may work for you assuming the string involved doesn't contain \. Treat the string as a filename, remove the "name+extension" then reverse the / to \ conversion.

Sign up to request clarification or add additional context in comments.

1 Comment

Not an issue with the example given, but this will fail if the string begins with a drive letter. Easily solved by using in ("a:\a%string%") and then after assigning "substring=%%~pa", remove the \a with %substring:~2%, and then convert \ back into /.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.