AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1512500
Accepted
tar
tar
Asked: 2019-12-26 11:36:21 +0800 CST2019-12-26 11:36:21 +0800 CST 2019-12-26 11:36:21 +0800 CST

Linha de comando: obtenha substring entre 2 delimitadores diferentes

  • 772

como posso obter uma substring entre dois delimitadores diferentes que também está em uma posição variável dentro de uma determinada string.

Por exemplo:

String1 = "my first example {{my first substring}}"
String2 = "my great second example which has much more words included before {{my second substring}} and after the substring"
Substring1 = "my first substring"
Substring2 = "my second substring"

Como você pode ver, o delimitador antes da substring é "{{" e o depois é "}}".

Tudo o que encontrei em relação às operações de substring são configurações de posição estritas que não ajudam aqui.

Desde já, obrigado!

command-line batch-file
  • 3 3 respostas
  • 625 Views

3 respostas

  • Voted
  1. Akina
    2019-12-26T12:18:22+08:002019-12-26T12:18:22+08:00
    @echo off
    cls
    setlocal ENABLEDELAYEDEXPANSION
    
    set String1=my first example {{my first substring}}
    set String2=my great second example which has much more words included before {{my second substring}} and after the substring
    
    call :extract %String1% 
    echo %Substring%
    call :extract %String2% 
    echo %Substring%
    
    endlocal
    goto :EOF
    
    :extract
    for /f "delims={ tokens=2" %%x in ("%*") do (
        set Substring=%%x
    )
    for /f "delims=}" %%x in ("%Substring%") do (
        set Substring=%%x
    )
    exit /b
    

    Eu não acredito que isso dê os resultados corretos. Por exemplo --- {{abc {123} xyz}} --- retorna abc, mas acho que o resultado correto é abc {123} xyz. - dbenham

    Isso mesmo. Para resolver esse problema, devemos ter algum caractere imprimível que esteja ausente na string de origem (pelo menos antes de finalizar o delimitador).

    Por exemplo, se tal char for @o código pode ser

    @echo off
    cls
    setlocal ENABLEDELAYEDEXPANSION
    
    set String1=my first example {{my first substring}}
    set String2=my great second example which has much more words included before {{my second substring}} and after the substring
    set String3=--- {{abc {123} xyz}} ---
    
    call :extract %String1% 
    echo %Substring%
    call :extract %String2% 
    echo %Substring%
    call :extract %String3% 
    echo %Substring%
    
    endlocal
    goto :EOF
    
    :extract
    set tempstr=%*
    set tempstr=%tempstr:{{=@%
    set tempstr=%tempstr:}}=@%
    for /f "delims=@ tokens=2" %%x in ("%tempstr%") do (
        set Substring=%%x
    )
    exit /b
    
    • 1
  2. tar
    2019-12-26T12:27:58+08:002019-12-26T12:27:58+08:00

    Acho que encontrei uma solução:

    set string="my great second example which has much more words included before {{my second substring}} and after the substring"
    echo string: %string%
    set "tmp=%string:{=" & set "tmp=%"
    echo tmp:    %tmp%
    for /f "delims=}" %%a in ("%tmp%") do set substr=%%a
    echo substr: %substr%
    

    Resultado:

    string: "my great second example which has much more words included before {{my second substring}} and after the substring"
    tmp:    "my great second example which has much more words included before "
    substr: my second substring
    

    Funciona, mas não entendo muito bem como é capaz de determinar a substring da tmp-string, pois não está em seu conteúdo.

    • 0
  3. Best Answer
    dbenham
    2019-12-27T14:46:40+08:002019-12-27T14:46:40+08:00

    Eu suponho que você só precisa de uma substring de cada string. Aqui está uma solução robusta que manipula qualquer valor, exceto que não pode manipular !o valor e também ^é removida se !estiver no valor.

    @echo off
    setlocal enableDelayedExpansion
    for %%S in (
      "my {{first substring}} example"
      "my {ignore {{second substring}} example"
      "my {{third {sub}string}} example"
      "poison character {{&|<>^^ "^&^|^<^>^^^^"}} example"
      "empty {{}} example"
      "my {first error}} example"
      "my {{second error} example"
      "my third error example{{"
      ""
      "Limitation: {{eclamation is stripped^^^!}}"
      "Limitation: {{caret ^^^^ is stripped if exclamation present^^^!}}"
    ) do (
      set "string=%%~S"
      echo(!string!
      call :get{{sub}} string sub && echo(!sub! || echo ERROR: substring not found
      echo(
    )
    exit /b
    
    :get{{sub}}  inStrVar  subStrVar
    setlocal enableDelayedExpansion
    set "str=!%~1!"
    if not defined str exit /b 1
    set "sub1=!str:*{{=!"
    if not defined sub1 exit /b 1
    if "!sub1!"=="!str!" exit /b 1
    set "sub="
    for %%N in (^"^
    
    ^") do for /f "delims=" %%A in ("x!sub1:}}=%%~N!") do if not defined sub set "sub=%%A"
    set "sub=!sub:~1!"
    if "!sub!"=="!sub1!" exit /b 1
    for /f delims^=^ eol^= %%A in (""!sub!"") do endlocal & set "%~2=%%~A" & exit /b 0
    

    -- RESULTADO --

    my {{first substring}} example
    first substring 
    
    my {ignore {{second substring}} example
    second substring 
    
    my {{third {sub}string}} example
    third {sub}string 
    
    poison character {{&|<>^ "&|<>^"}} example
    &|<>^ "&|<>^" 
    
    empty {{}} example
    
    
    my {first error}} example
    ERROR: substring not found
    
    my {{second error} example
    ERROR: substring not found
    
    my third error example{{
    ERROR: substring not found
    
    
    ERROR: substring not found
    
    Limitation: {{eclamation is stripped!}}
    eclamation is stripped 
    
    Limitation: {{caret ^ is stripped if exclamation present!}}
    caret  is stripped if exclamation present 
    

    Existem dois truques principais para obter a substring.

    • !str:*{{!exclui tudo na primeira ocorrência de {{.
    • for %%N in ...cria uma nova linha entre aspas %%Npara que a !sub:{{=%%~N!nova linha substitua todos os }}. O interno for /fentão itera cada string separadamente e o doloop mantém apenas o primeiro resultado. O xé anexado apenas no caso de a substring estar vazia.
    • 0

relate perguntas

  • Como fazer um script em lote para fazer backup de um arquivo específico com uma pasta de destino exclusiva (windows) [fechado]

  • Como posso alternar Handoff (Continuidade) no Terminal no macOS?

  • Existe um dispositivo ou executável no Windows que pode fornecer bytes aleatórios criptograficamente seguros via CMD ou Powershell?

  • Qual seria o equivalente em lote do argumento "pass" do Python?

  • Não é possível ativar o Microsoft Print to PDF depois de desativado

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    Serviço do Windows 10 chamado AarSvc_70f961. O que é e como posso desativá-lo?

    • 2 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Marko Smith

    ssl.SSLCertVerificationError: falha na verificação do certificado [SSL: CERTIFICATE_VERIFY_FAILED]: não foi possível obter o certificado do emissor local (_ssl.c:1056)

    • 4 respostas
  • Marko Smith

    Como posso saber em qual unidade o Windows está instalado?

    • 6 respostas
  • Martin Hope
    Albin Como faço para ativar o WindowsXP agora que o suporte acabou? 2019-11-18 03:50:17 +0800 CST
  • Martin Hope
    fixer1234 O "HTTPS Everywhere" ainda é relevante? 2019-10-27 18:06:25 +0800 CST
  • Martin Hope
    Kagaratsch O Windows 10 exclui muitos arquivos minúsculos muito lentamente. Algo pode ser feito para agilizar? 2019-09-23 06:05:43 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    Inter Sys Como Ctrl+C e Ctrl+V funcionam? 2019-05-15 02:51:21 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve