You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

批处理脚本提取未知数量点分隔符的最后一个令牌问题

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, lastToken gets updated to the current token—by the end of the loop, it'll hold the very last token from your original string.
  • %%~t strips 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 lastToken to the current first token and replace name with the remaining part.
  • Once name is empty, lastToken will be the final token from your original input—perfect for both "Bob.Smith" and "Bob.J.Smith" cases.

内容的提问来源于stack exchange,提问作者Mike B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:21:18