-1

Galera como faço para pegar bloco por bloco de um txt com esse formato ? Eu tenho que pegar até a ultima data. As vezes vem duas datas em cada bloco

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAAAA em: 20/04/2017

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAAA em: 20/04/2017
AAAAAAAAAAAAAAAAAAAAAAAA
AAAAAA em: 21/06/2016

AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAA em: 20/04/2017


AAAAAAAAAA AAAAAAAAAAA - AAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAA
AAAAAA em: 20/04/2017
4
  • Quais são exatamente os valores que você pretende pegar do texto? Todas as datas? Se sim, elas estão sempre neste formado dd/mm/YYYY?
    – Woss
    29/11/2017 às 18:57
  • Cada data é formada por linhas consecutivas? Separando blocos com linha em branco? 29/11/2017 às 18:59
  • Um bloco pode ter mais de uma data.
    – use777
    29/11/2017 às 19:02
  • E na verdadeo não tem espaço entre os blocos. Coloquei aqui com epaço para ficar mais visivel.
    – use777
    29/11/2017 às 19:02

2 Respostas 2

-1

Como o flavor não foi especificado, o Excel VBA foi usado, que usa javascript.

Regex

Habilitar o Regex no Excel

  1. RegEx precisa ser habilitado, Habilite o modo Desenvolvedor
  2. Na aba 'Desenvolvedor', clique em 'Visual Basic' e a janela do VBA irá abrir.
  3. Vá em 'Ferramentas' -> 'Referências...' e uma janela abrirá.
  4. Procure por 'Microsoft VBScript Regular Expressions 5.5', como na imagem abaixo. E habilite esta opção.

Janela Referências

Padrão

Um Regex simples que identifica se possui números:

Demo no Regex101 e o padrão: \d{2}\/\d{2}\/\d{4}

Código em Excel VBA

Validar Dados

Este padrão somente pega uma string no formato 2números/2números/4números e a validação da Data, para verificar se a mesma é válida, é realizada pelo Excel com o IsDate().

O IsDate pode causar alguns erros (Pois tenta verificar se é data em formatos universais, de vários países...), refira a esta resposta para outra forma de verificar se é data.

Sub ValidarDados()

    Dim objStream As Object
    Dim strData As String
    Dim fileName As String, textData As String, fileNo As Integer
    sFilename = "temp.txt"
    sFilepath = ThisWorkbook.Path & "\" & sFilename
    fileNo = FreeFile                            'Get first free file number


Inicio:
    If Dir(sFilepath) <> "" Then
        Open sFilepath For Input As #fileNo
        strData = Input$(LOF(fileNo), fileNo)

        Dim objMatches As Object, objRegExp As Object
        Set objRegExp = CreateObject("VBScript.RegExp")
        'Regex
        objRegExp.Pattern = "\d{2}\/\d{2}\/\d{4}"
        objRegExp.Global = True

        Set objMatches = objRegExp.Execute(strData)
        If objMatches.Count <> 0 Then
            For Each m In objMatches
                If IsDate(m) Then MsgBox m 'Debug.Print m
            Next m
        End If
    Else
        MsgBox "O arquivo não pôde ser carregado - Escolha o arquivo."
        strPath = EscolherCaminho
        GoTo Inicio
    End If
    'Close
    Close #fileNo

End Sub

Escolher Caminho

Caso não encontre o caminho referido no código, uma janela será aberta para escolher o arquivo no sistema.

Public Function EscolherCaminho() As String
    'Créditos: http://software-solutions-online.com/excel-vba-open-file-dialog/
    Dim intChoice As Long
    Dim strPath As String

    'only allow the user to select one file
    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
    'make the file dialog visible to the user
    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    'determine what choice the user made
    If intChoice <> 0 Then
        'get the file path selected by the user
        strPath = Application.FileDialog( _
                  msoFileDialogOpen).SelectedItems(1)
        'print the file path to sheet 1
        EscolherCaminho = strPath
    End If
End Function

Resultados

Com estes dados encontrados num teste no txt:

  • 20/04/2017
  • 20/04/2017
  • 21/06/2016
  • 20/04/2017
  • 20/04/2017
  • 32/04/2017
  • 30/02/2017
  • 20/13/2017

Após a validação com IsDate(), são estes resultados:

  • 20/04/2017
  • 20/04/2017
  • 21/06/2016
  • 20/04/2017
  • 20/04/2017
-1

regex: (((0[1-9]|[12][0-9]|3[01])[- /.](0[13578]|1[02])|(0[1-9]|[12][0-9]|30)[- /.](0[469]|11)|(0[1-9]|1\d|2[0-8])[- /.]02)[- /.]\d{4}|29[- /.]02[- /.](\d{2}(0[48]|[2468][048]|[13579][26])|([02468][048]|[1359][26])00))

para testar: https://regexr.com/

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .