批处理脚本提取未知数量点分隔符的最后一个令牌问题
Extracting the Last Token from a Dot-Separated String in Batch
Your current script is grabbing everything up to the first dot instead of the last token—let's fix that with a couple of reliable approaches. Here's a simple, clean script that works no matter how many dots are in your input string:
@echo off SETLOCAL ENABLEDELAYEDEXPANSION set "name=%USERNAME%" :: Replace dots with quoted spaces to split into individual tokens set "temp=!name:.=" "!" :: Loop through each token; the last iteration will hold our final value set "lastToken=" for %%t in (!temp!) do set "lastToken=%%~t" :: Assign the last token back to the name variable set "name=!lastToken!" echo !name! ENDLOCAL
How this works:
set "temp=!name:.=" "!": This uses batch's built-in variable substitution to swap every.with" "(quote-space-quote). For example, "Bob.J.Smith" turns into"Bob" "J" "Smith".- The
for %%t in (!temp!)loop goes through each quoted token. Every time it runs,lastTokengets updated to the current token—by the end of the loop, it'll hold the very last token from your original string. %%~tstrips off the surrounding quotes from each token, giving us a clean value without extra punctuation.
If you need a method that's more robust for strings with special characters, here's an alternative loop-based approach:
@echo off SETLOCAL ENABLEDELAYEDEXPANSION set "name=%USERNAME%" set "lastToken=" :splitLoop :: Split the string into the first token and everything that comes after for /f "tokens=1* delims=." %%a in ("!name!") do ( set "lastToken=%%a" set "name=%%b" ) :: Keep looping until there's nothing left to split if not "!name!"=="" goto splitLoop set "name=!lastToken!" echo !name! ENDLOCAL
How this works:
- We keep splitting the string into two parts: the first token (
%%a) and the rest of the string (%%b). - Each time we split, we update
lastTokento the current first token and replacenamewith the remaining part. - Once
nameis empty,lastTokenwill be the final token from your original input—perfect for both "Bob.Smith" and "Bob.J.Smith" cases.
内容的提问来源于stack exchange,提问作者Mike B
相关产品推荐
相关产品推荐

