sábado, 30 de maio de 2026

REGEX - pegando somente o nome do arquivo de um caminho sem extensão

Solução gerado pelo GEMINI


====== Arquivo local

DATA lv_file TYPE string.
lv_file = 'c:\temp\programa\teste.txt'.

" We use [^\\]+ to ensure it only captures characters that are NOT backslashes
DATA(lv_filename) = replace( val   = lv_file
                             regex = `.*\\([^\\]+)\.[^.]+$`
                             with  = `$1` ).

WRITE: / 'Extracted Name:', lv_filename. " Output: teste



====== Arquivo servidor

DATA lv_file TYPE string.
lv_file = '/sap/usr/files/teste.txt'.

" This regex works for BOTH 'c:\temp\teste.txt' and '/sap/usr/teste.txt'
DATA(lv_filename) = replace( val   = lv_file
                             regex = `.*[/\\]([^/\\]+)\.[^.]+$`
                             with  = `$1` ).

WRITE: / 'Extracted Name:', lv_filename. " Output: teste


  • .*\\ : Eats up everything until a backslash.

  • ([^\\]+) : Capture Group 1. Captures 1 or more characters that are NOT a backslash (teste). Because it refuses to capture backslashes, it is forced to only look at the very last part of the path.

  • \.[^.]+$ : Matches the literal dot and the extension at the end of the string.

  • Nenhum comentário:

    Postar um comentário