Easier way to parse string?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Easier way to parse string?

#1 Post by SIMMS7400 » 20 Aug 2017 08:11

Hi Folks -

I need to extract the string between the first "-" and first "." characters.

Here is my code but was wondering if there was a cleaner way?

Thanks!

Code: Select all

@ECHO OFF
SET "PBCS_URL_PELPRD1=https://sample-planning.pbcs.us2.oraclecloud.com"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "tokens=2-4* delims=/" %%A IN ("%PBCS_URL_PELPRD1%") DO (
   SET "P1=%%A"
   FOR /f "tokens=2-4* delims=-" %%B IN ("!P1!") DO (
      SET P2=%%B
      FOR /f "tokens=1-4* delims=." %%C IN ("!P2!") DO (
         SET DOMAIN=%%C
      )
   )
)

ECHO !DOMAIN!
pause

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Easier way to parse string?

#2 Post by aGerman » 20 Aug 2017 08:30

Two FOR /F loops should be sufficient.

Code: Select all

for /f "delims=." %%A in ("%PBCS_URL_PELPRD1%") do for /f "tokens=1* delims=-" %%B in ("%%A") do set "DOMAIN=%%C"

Steffen

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Easier way to parse string?

#3 Post by Aacini » 20 Aug 2017 08:46

I don't understand what your example code does, but this line extract the part between the first "-" and the first "." (assuming that the first "." is placed after the first "-"):

Code: Select all

for /F "delims=." %%a in ("%PBCS_URL_PELPRD1:*-=%") do set "DOMAIN=%%a"

Antonio

SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Re: Easier way to parse string?

#4 Post by SIMMS7400 » 20 Aug 2017 11:04

Thank you both!

I do have one tweak we could do perhaps.

There are times when there are (2) "-" characters before the first ".". Could make a check where it says if there are (2) "-", use string AFTER the second one?

Thanks!

Code: Select all

SET "PBCS_URL_PLNGTST=https://planning-test-a503671.pbcs.us6.oraclecloud.com"

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Easier way to parse string?

#5 Post by aGerman » 20 Aug 2017 11:49

There is a technique using the replace syntax that helps to get always the last token.

Code: Select all

@echo off &setlocal
SET "PBCS_URL_PLNGTST=https://planning-test-a503671.pbcs.us6.oraclecloud.com"

for /f "delims=." %%A in ("%PBCS_URL_PLNGTST%") do set "DOMAIN=%%A"
set "DOMAIN=%DOMAIN:-=" & set "DOMAIN=%"

echo %DOMAIN%
pause

Steffen

SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Re: Easier way to parse string?

#6 Post by SIMMS7400 » 20 Aug 2017 13:34

That worked perfectly!!! Thank you so much - have a great rest of your Sunday!

Post Reply