Página 1 de 1

Pegar pedaços de uma string

Enviado: 05 Ago 2018 19:38
por Itamar M. Lins Jr.
Ola!
Como eu faço para pegar as partes desta string ?

Código: Selecionar todos

 apelido=itamar&usuario=itamar+lins&senha=123456
No caso, cApelido := "itamar", cUsuario := "itamar lins" ...
Sei que existe a função at(), etc...
Mas eu acho que tem umas funções prontas as tais tokens...
Enquanto pergunto vou na net e achei esse site.
https://github.com/zgamero/sandbox/wiki ... --atokens_

Muito legal!

Saudações,
Itamar M. Lins Jr.

Pegar pedaços de uma string

Enviado: 10 Ago 2018 13:04
por bencz
Ou implementar uma simples função para fazer o 'split' (:

Código: Selecionar todos

STATIC FUNCTION split( cString, cSeparator )
   LOCAL nPos
   LOCAL aString := {}
   DEFAULT cSeparator := ";"
   cString := ALLTRIM( cString ) + cSeparator
   DO WHILE .T.
      nPos := AT( cSeparator, cString )
      IF nPos = 0
         EXIT
      ENDIF
      AADD( aString, SUBSTR( cString, 1, nPos-1 ) )
      cString := SUBSTR( cString, nPos+1 )
   ENDDO
RETURN ( aString )
Eu encontrei essa função, em algum lugar, não sei se foi aqui no forum ou em algum lugar na internet...

Pegar pedaços de uma string

Enviado: 12 Ago 2018 21:38
por JoséQuintas
Acho que a princícpio seriam 3 etapas.

1) Separar os conjuntos &

Código: Selecionar todos

aParam := hb_RegExSplit( "&", cTexto )
{ ;
"apelido=Itamar", ;
"usuario=itamar+lins", ;
"senha=123456" }

2) Separar o nome do valor

Código: Selecionar todos

xParam := hb_RegExSplit( "=", cTexto )

{ ;
{ "apelido", "Itamar" }, ;
{ "usuario", "Itamar+lins" }, ;
{ "senha", "123456" } }

3) O ajuste final, trocando + por espaço

Código: Selecionar todos

cText := StrTran( cText, "+", " " )
Completo:

Código: Selecionar todos

PROCEDURE main

   LOCAL aList, xValue, cText

   cText := "apelido=itamar&usuario=itamar+lins&senha=123456"
   aList := hb_RegExSplit( "&", cText )
   FOR EACH xValue IN aList
      xValue := hb_RegExSplit( "=", xValue )
      xValue[ 2 ] := StrTran( xValue[ 2 ], "+", " " )
      ? xValue[ 1 ], xValue[ 2 ]
   NEXT

   Inkey(0)
test.png

Pegar pedaços de uma string

Enviado: 13 Ago 2018 09:29
por Itamar M. Lins Jr.
Ola!
Beleza, não sabia dessa função hb_regexsplit

Saudações,
Itamar M. Lins Jr.

Pegar pedaços de uma string

Enviado: 17 Set 2018 12:38
por Itamar M. Lins Jr.
Ola!
Continuando com os estudos em CGI, temos diversas maneiras de conversar com paginas em HTML + Apache2 + Harbour essa é mais uma que estou aprendendo.

Código: Selecionar todos

#!/usr/local/bin/hbrun
REQUEST HB_CODEPAGE_UTF8 
function main(...)
LOCAL cEOL := + hb_eol() + hb_eol()
LOCAL cTemp, nRead, nLen, aList, xValue
hb_cdpSelect( "UTF8" ) 
OutStd('Content-type: text/html' + cEOL )
OutStd('<!DOCTYPE html>' + hb_eol() )
OutStd('<html>' + hb_eol() )
OutStd('<head>' + hb_eol() )
OutStd('<meta charset="UTF-8"/>' + hb_eol())
OutStd('</head>' + hb_eol() )

IF "POST" $ Upper( hb_GetEnv( "REQUEST_METHOD" ) ) //aqui retirada da hbtip
   nLen := val(hb_getenv("CONTENT_LENGTH"))
   cTemp := Space( nLen )
   IF ( nRead := FRead( hb_GetStdIn(), @cTemp, nLen ) ) != nLen
      OutStd("<p>Post error read " + hb_ntos( nRead ) + " instead of " + hb_ntos( nLen )  + hb_eol() )    
   ELSE
      OutStd("<p>Post string is: " , HtmlDecodeUrl(cTemp) + hb_eol())      
   ENDIF
ENDIF
OutStd('<br>')

aList := hb_RegExSplit( "&", cTemp )
FOR EACH xValue IN aList
    xValue := hb_RegExSplit( "=", xValue )
    xValue[ 2 ] := StrTran( xValue[ 2 ], "+", " " )
    OutStd( xValue[ 1 ], HtmlDecodeUrl(xValue[ 2 ]) + "<br>"+  hb_eol())
NEXT

OutStd("</body></html>" + hb_eol())

Return Nil

FUNCTION HtmlDecodeUrl( cString ) //Acrescentei alguns caracteres acentuados nesta função. Retirada de uma classe da xhb.hbc
   RETURN hb_StrReplace( cString, { ;
      "%26" => "&", ;
      "%2B" => "+", ;
      "%20" => " ", ;
      "%27" => "'", ;
      "+"   => " ", ;
      "%2C" => ",", ;
      "%21" => "!", ;
      "%7E" => "~", ;
      "%23" => "#", ;
      "%24" => "!", ;
      "%25" => "%", ;
      "%5E" => "^", ;
      "%28" => "(", ;
      "%29" => ")", ;
      "%60" => "`", ;
      "%2F" => "/", ;
      "%C3%A0" => "à",;
      "%C3%A1" => "á",;
      "%C3%A2" => "â",;      
      "%C3%A3" => "ã",;
      "%C3%80" => "À",;
      "%C3%81" => "Á",;
      "%C3%82" => "Â",;
      "%C3%83" => "Ã",;
      "%C3%A8" => "è",;
      "%C3%A9" => "é",;
      "%C3%AA" => "ê",;
      "%E1%BA%BD" => "ẽ",;
      "%C3%89" => "É",;
      "%C3%88" => "È",;
      "%C3%A7" => "ç",;
      "%C3%87" => "Ç",;
      "%C3%8A" => "Ê",;
      "%E1%BA%BC" => "Ẽ",;
      "%C3%8C" => "Ì",;
      "%C3%8D" => "Í",;
      "%C3%8E" => "Î",;
      "%C4%A8" => "Ĩ",;
      "%C3%B2" => "ò",;
      "%C3%B3" => "ó",;
      "%C3%B4" => "ô",;
      "%C3%B5" => "õ",;
      "%C3%92" => "Ò",;
      "%C3%93" => "Ó",;
      "%C3%94" => "Ô",;
      "%C3%95" => "Õ",;
      "%C3%BA" => "ú",;
      "%C3%B9" => "ù",;
      "%C5%A9" => "ũ",;
      "%C3%BB" => "û",;
      "%C3%9A" => "Ú",;
      "%C3%99" => "Ù",;
      "%C5%A8" => "Ũ",;
      "%C3%9B" => "Û"})    
Isso é um estudo de como pegar os dados da pagina HTML, temos hb_tip, hbhttpd... com funções básicas para essa finalidade.

Saudações,
Itamar M. Lins Jr.

Pegar pedaços de uma string

Enviado: 17 Set 2018 14:15
por asimoes
Voltando ao assunto,

Tem como fazer split usando a função hb_RegExSplit() ? onde:

Código: Selecionar todos

SELECT
   SELECT
   FROM
   WHERE
WHERE
UNION
...
ORDER BY 

Código: Selecionar todos

  cQuery := "SELECT T.DATPREVPG, T.DT_VENCTO, T.* FROM (                                         "
   cQuery += "SELECT PS.*                                                                         "
   cQuery += " FROM  PAGAMENTO_FIN PS                                                             "
   cQuery += " WHERE PS.DATPREVPG >= ?                                                            "
   cQuery += "   AND PS.DATPREVPG <= ?                                                            "
   cQuery += "   AND PS.RETENCAO = 'S'                                                            "
   cQuery += "   AND PS.NUM_PROC_PR IS NOT NULL                                                   "
   cQuery += "   AND PS.BLOQUEADA IS NULL                                                         "
   cQuery += "   AND PS.NUMCHEQUE IS NULL                                                         "
   cQuery += "   AND PS.DATPG IS NULL                                                             "
   cQuery += "   AND PS.RETIRADA IS NULL                                                          "
   cQuery += "UNION                                                                               "
   cQuery += "SELECT P.*                                                                          "
   cQuery += " FROM PAGAMENTO_FIN P                                                               "
   cQuery += " WHERE P.RETENCAO = 'S'                                                             "
   cQuery += "   AND P.BLOQUEADA IS NULL                                                          "
   cQuery += "   AND P.NUMCHEQUE IS NULL                                                          "
   cQuery += "   AND P.DATPG IS NULL                                                              "
   cQuery += "   AND P.RETIRADA IS NULL                                                           "
   cQuery += "   AND EXISTS                                                                       "
   cQuery += "       (                                                                            "
   cQuery += "            SELECT 1                                                                "
   cQuery += "             FROM  PAGAMENTO_FIN PS1                                                "
   cQuery += "             WHERE PS1.DATPREVPG >= ?                                               "
   cQuery += "               AND PS1.DATPREVPG <= ?                                               "
   cQuery += "               AND PS1.RETENCAO = 'S'                                               "
   cQuery += "               AND PS1.NUM_PROC_PR IS NOT NULL                                      "
   cQuery += "               AND PS1.BLOQUEADA   IS NULL                                          "
   cQuery += "               AND PS1.NUMCHEQUE   IS NULL                                          "
   cQuery += "               AND PS1.DATPG       IS NULL                                          "
   cQuery += "               AND PS1.RETIRADA    IS NULL                                          "
   cQuery += "               AND P.NUMPROC    = PS1.NUM_PROC_PR                                   "
   cQuery += "               AND P.NUMOP      = PS1.NUM_LIQ_PRI                                   "
   cQuery += "               AND P.EMPENHO    = PS1.NUM_EMP_PRI                                   "
   cQuery += "               AND P.ORGAO_UNID = PS1.ORG_UNI_PRI                                   "
   cQuery += "               AND P.EXERCICIO  = PS1.EXERC_PRI                                     "
   cQuery += "         ) ) T                                                                      "
   cQuery += "ORDER BY T.DATPREVPG,                                                               "
   cQuery += "         decode(T.DT_VENCTO, null, TO_DATE('30/12/1889', 'DD/MM/YYYY'), T.DT_VENCTO)"

Pegar pedaços de uma string

Enviado: 17 Set 2018 14:39
por Itamar M. Lins Jr.
Ola!
hb_RegExSplit() ?
Essa função retorna uma array.
Não entendi o uso ai que vc quer. É tipo strtran() só que vem em array o resultado. (salvo engano)
http://www.kresin.ru/en/hrbfaq_3.html#Doc9

Saudações,
Itamar M. Lins Jr.

Pegar pedaços de uma string

Enviado: 17 Set 2018 14:55
por asimoes
Itamar

Pra ficar +- do jeito que eu quero coloquei um Hb_Eol() no final de cada linha, ai eu faço o split com Hb_Eol(), a ideia é gerar um txt da query quando precisar, pra colar no plsql-developer quando precisar testar uma query tipo a que eu postei. Tem maiores que esta.

Pegar pedaços de uma string

Enviado: 17 Set 2018 16:18
por JoséQuintas
asimoes escreveu:um Hb_Eol() no final de cada linha, ai eu faço o split com Hb_Eol(), a ideia é gerar um txt
Ué... se já tem hb_Eol()... tá pronto, não precisa mais nada

hb_MemoWrit( "teste.txt", cComandoSql )

Pegar pedaços de uma string

Enviado: 17 Set 2018 16:28
por JoséQuintas
Automático pra um comando desses vai ser complicado.

Talvez alguns testes pra ver se ajuda, tipo....

Código: Selecionar todos

cCmd := StrTran( cCmd, "SELECT ", hb_Eol() + "SELECT " )
cCmd := StrTran( cCmd, " FROM ", hb_Eol() + " FROM " )
cCmd := StrTran( cCmd, " GROUP BY ", hb_Eol() + " GROUP BY " )
cCmd := StrTran( cCmd, " ORDER BY ", hb_Eol() + " ORDER BY " )
Mas pode complicar se não for palavra única.
Pode existir uma empresa com o nome "SELECT E CIA LTDA" ou "QUINTAS GROUP INC" e já vai atrapalhar tudo.

Pegar pedaços de uma string

Enviado: 14 Jun 2024 15:19
por clodoaldomonteiro
Boas a todos.

contribuindo aqui com o post.

Estava tentando usar a função do xHarbour "HB_ATokens()", que é similar à função que Quintas passou aqui "hb_RegExSplit()" mas vi uma diferença interessante, que é o limite do tamanho das células, pois a função HB_ATokens() tem o limite de 4096 caracteres por célula e função hb_RegExSplit() não tem limite.

Abreços.

Pegar pedaços de uma string

Enviado: 14 Jun 2024 18:54
por ivanil
Desenterrou legal esse post Clodoaldo...
clodoaldomonteiro escreveu:Pegar pedaços de uma string
por clodoaldomonteiro » 14 Jun 2024 15:19

Boas a todos.

contribuindo aqui com o post.

Estava tentando usar a função do xHarbour "HB_ATokens()", que é similar à função que Quintas passou aqui "hb_RegExSplit()" mas vi uma diferença interessante, que é o limite do tamanho das células, pois a função HB_ATokens() tem o limite de 4096 caracteres por célula e função hb_RegExSplit() não tem limite.
Depois refaça seu teste, as arrays hoje já tem mais relação com memória disponível...
Um adendo entre uma funcão e outra, bom lembrar que hb_atokens tem o 3 e 4 parâmetros que tratam string;
um dos exemplos dos colegas foi dar um strtran em + para espaço, porem o + poderia ser parte da senha; embora seja possível tratar isso em registro, eu não tenho familiaridade e meus problemas hb_atokens resolve.

O exemplo abaixo acrescentei uma célula com o tamanho de 120.008; sem problemas.