ScriptForge.String serviço

O serviço String disponibiliza um conjunto de métodos para o processamento de cadeias de caracteres. Estes métodos podem ser utilizados para:

Definições

Quebras de linha

O serviço String reconhece as seguintes quebras de linha:

Nome simbólico

Número ASCII

Avanço de linha
Tabulação vertical
Retorno de carro
Retorno de carro + Avanço de linha
Separador de ficheiro
Separador de grupo
Separador de registo
Linha seguinte
Separador de linha
Separador de parágrafo

10
12
13
13 + 10
28
29
30
133
8232
8233


Espaços em branco

O serviço String reconhece os seguintes espaços em branco:

Nome simbólico

Número ASCII

Espaço
Tabulação horizontal
Avanço de linha
Tabulação vertical
Avanço de página
Retorno de carro
Linha seguinte
Espaço não separável
Separador de linha
Separador de parágrafo

32
9
10
11
12
13
133
160
8232
8233


Sequências de escape

Segue-se uma lista de sequências de escape que podem ser utilizadas em cadeias de caracteres.

Sequência de escape

Nome simbólico

Número ASCII

\n
\r
\t

Avanço de linha
Retorno de carro
Tabulação horizontal

10
13
9


Ícone da dica

Para que a sequência de escape «\n» seja interpretada como uma cadeia de caracteres propriamente dita, basta utilizar «\\n» em vez de "\" & Chr(10).


Caracteres não imprimíveis:

Os caracteres definidos na Base de Dados de Caracteres Unicode como «Outros» ou «Separadores» são considerados caracteres não imprimíveis.

Os caracteres de controlo (código ASCII <= 0x1F) também são considerados não imprimíveis.

Aspas dentro de cadeias de caracteres:

Para inserir aspas nas cadeias de caracteres, utilize \' (aspas simples) ou \" (aspas duplas). Por exemplo:

Chamada de serviço

Antes de utilizar o serviço ScriptForge.String, é necessário carregar a biblioteca ScriptForge da seguinte forma:

Em Basic

      GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
  

Ao carregar a biblioteca, será criado o objeto SF_String, que pode ser utilizado para chamar os métodos do serviço String.

Os trechos de código seguintes mostram as três formas de chamar métodos do serviço String (o método Capitalize é utilizado como exemplo):


    Dim s as String : s = "abc def"
    s = SF_String.Capitalize(s) ' Abc Def
  

    Dim s as String : s = "abc def"
    Dim svc : svc = SF_String
    s = svc.Capitalize(s) ' Abc Def
  

    Dim s as String : s = "abc def"
    Dim svc : svc = CreateScriptService("String")
    s = svc.Capitalize(s) ' Abc Def
  
Em Python

O fragmento de código abaixo ilustra como invocar métodos do serviço String em scripts Python. O método IsIPv4 é utilizado como exemplo.


    from scriptforge import CreateScriptService
    svc = CreateScriptService("String")
    ip_address = '192.168.0.14'
    svc.IsIPv4(ip_address) # True
  

Propriedades

O objeto SF_String disponibiliza as seguintes propriedades para scripts em Basic:

Nome

Apenas leitura

Descrição

sfCR

Sim

Retorno de carro: Chr(13)

sfCRLF

Sim

Retorno de carro + Avanço de linha: Chr(13) e Chr(10)

sfLF

Sim

Avanço de linha: Chr(10)

sfNEWLINE

Sim

Retorno de carro + avanço de linha, que pode ser
1) Chr(13) e Chr(10) ou
2) avanço de linha: Chr(10)
dependendo do sistema operativo.

sfTAB

Sim

Tabulação horizontal: Chr(9)


Ícone da dica

Pode utilizar as propriedades acima para identificar ou inserir os caracteres correspondentes dentro de cadeias de caracteres. Por exemplo, o avanço de linha pode ser substituído por SF_String.sfLF.


Lista de métodos do serviço String

Capitalize
Count
EndsWith
Escape
ExpandTabs
FilterNotPrintable
FindRegex
HashStr
HtmlEncode
IsADate
IsAlpha
IsAlphaNum
IsAscii
IsDigit
IsEmail

IsFileName
IsHexDigit
IsIBAN
IsIPv4
IsLike
IsLower
IsPrintable
IsRegex
IsSheetName
IsTitle
IsUpper
IsUrl
IsWhitespace
JustifyCenter
JustifyLeft

JustifyRight
Quote
ReplaceChar
ReplaceRegex
ReplaceStr
Represent
Reverse
SplitLines
SplitNotQuoted
StartsWith
TrimExt
Unescape
Unquote
Wrap


Ícone de nota

O primeiro argumento da maioria dos métodos é a cadeia de caracteres a ser considerada. É sempre passado por referência e permanece inalterado. Métodos como Capitalize, Escape, etc., devolvem uma nova cadeia de caracteres após a sua execução.


Ícone de aviso

Como o Python dispõe de um suporte abrangente a cadeias de caracteres integrado, a maioria dos métodos do serviço String está disponível apenas para scripts Basic. Os métodos disponíveis para Basic e Python são: HashStr, IsADate, IsEmail, IsFileName, IsIBAN, IsIPv4, IsLike, IsSheetName, IsUrl, SplitNotQuoted e Wrap.


Capitalize

Coloca em maiúscula o primeiro carácter de cada palavra na cadeia de caracteres introduzida.

Sintaxe:

svc.Capitalize(inputstr: str): str

Parâmetros:

inputstr: A cadeia de caracteres a que se pretende aplicar maiúsculas.

Exemplo:


    Dim sName as String : sName = "john smith"
    Dim sCapitalizedName as String
    sCapitalizedName = SF_String.Capitalize(sName)
    MsgBox sCapitalizedName 'John Smith
  

Count

Conta o número de ocorrências de uma subcadeia ou de uma expressão regular numa cadeia de caracteres.

Sintaxe:

svc.Count(inputstr: str, substring: str, [isregex: bool], [casesensitive: bool]): int

Parâmetros:

inputstr: A cadeia de caracteres de entrada a ser analisada

substring: A substring ou a expressão regular a utilizar durante a pesquisa

isregex: Utilize True se a subcadeia for uma expressão regular (Predefinição = False)

distingue maiúsculas e minúsculas: A pesquisa pode distinguir ou não maiúsculas e minúsculas (predefinição = False).

Exemplo:


    'Conta o número de ocorrências da subcadeia «or» dentro da cadeia de caracteres de entrada (retorna 2)
    MsgBox SF_String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "or", CaseSensitive := False)
    'Conta o número de palavras compostas apenas por letras minúsculas (retorna 7)
    MsgBox SF_String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", IsRegex := True, CaseSensitive := True)
  
Ícone da dica

Para saber mais sobre expressões regulares, consulte a documentação do Python em Operações com expressões regulares.


EndsWith

Devolve True se uma cadeia terminar com uma subcadeia especificada.

A função devolve False quando a cadeia de caracteres ou a subcadeia têm um comprimento igual a 0 ou quando a subcadeia é mais longa do que a cadeia de caracteres.

Sintaxe:

svc.EndsWith(inputstr: str, substring: str, [casesensitive: bool]): bool

Parâmetros:

inputstr: A cadeia de caracteres a testar.

substring: A substring a procurar no final de inputstr.

distingue maiúsculas e minúsculas: A pesquisa pode distinguir ou não maiúsculas e minúsculas (predefinição = False).

Exemplo:


    «Devolve "True" porque o método foi chamado com o valor predefinido de CaseSensitive = False»
    MsgBox SF_String.EndsWith("abcdefg", "EFG")
    'Devolve «False» devido ao parâmetro «CaseSensitive»
    MsgBox SF_String.EndsWith("abcdefg", "EFG", CaseSensitive := True)
  

Escape

Converte as quebras de linha e as tabulações contidas na cadeia de caracteres de entrada nas respetivas sequências de escape equivalentes (\\, \n, \r, \t).

Sintaxe:

svc.Escape(inputstr: str): str

Parâmetros:

inputstr: A cadeia de caracteres a converter.

Exemplo:


    'Devolve a cadeia de caracteres "abc\n\tdef\\n"
    MsgBox SF_String.Escape("abc" & Chr(10) & Chr(9) & "def\n")
  

ExpandTabs

Substitui os caracteres de tabulação Chr(9) por espaços, para reproduzir o comportamento dos pontos de tabulação.

Se for detetada uma quebra de linha, inicia-se uma nova linha e o contador de caracteres é reiniciado.

Sintaxe:

svc.ExpandTabs(inputstr: str, [tabsize: int]): str

Parâmetros:

inputstr: A cadeia de caracteres a expandir

tabsize: Este parâmetro é utilizado para determinar os pontos de tabulação através da fórmula: TabSize + 1, 2 * TabSize + 1, ... N * TabSize + 1 (Predefinição = 8)

Exemplo:


    Dim myText as String
    myText = "100" & SF_String.sfTAB & "200" & SF_String.sfTAB & "300" & SF_String.sfNEWLINE & _
             "X"  & SF_String.sfTAB & "Y" & SF_String.sfTAB & "Z"
    MsgBox SF_String.ExpandTabs(myText)
    '100     200     300
    'X       Y       Z
  

FilterNotPrintable

Substitui todos os caracteres não imprimíveis na cadeia de caracteres de entrada por um determinado caractere.

Sintaxe:

svc.FilterNotPrintable(inputstr: str, [replacedby: str]): str

Parâmetros:

inputstr: A cadeia de caracteres a pesquisar

replacedby: Zero, um ou mais caracteres que substituirão todos os caracteres não imprimíveis em inputstr (Predefinição = "")

Exemplo:


    Dim LF : LF = Chr(10)
    Dim myText as String
    myText = "àén ΣlPµ" & LF & " Русский" & "\n"
    MsgBox SF_String.FilterNotPrintable(myText)
    ' "àén ΣlPµ Русский\n"
  

FindRegex

Encontra numa cadeia de caracteres uma subcadeia que corresponda a uma expressão regular especificada.

Sintaxe:

svc.FindRegex(inputstr: str, regex: str, [start: int], [casesensitive: bool], [forward: bool]): str

Parâmetros:

inputstr: A cadeia de caracteres a pesquisar

regex: A expressão regular

start: A posição na cadeia de caracteres onde a pesquisa terá início. Este parâmetro é passado por referência, pelo que, após a execução, o valor de start apontará para o primeiro carácter da subcadeia encontrada. Se não for encontrada nenhuma subcadeia correspondente, start será definido como 0.

distingue maiúsculas e minúsculas: A pesquisa pode distinguir ou não maiúsculas e minúsculas (predefinição = False).

para a frente: Determina a direção da pesquisa. Se for True, a pesquisa avança. Se for False, a pesquisa recua (Predefinição = True)

Na primeira iteração, se forward = True, então start deve ser igual a 1; por outro lado, se forward = False, então start deve ser igual a Len(inputstr)

Exemplo:


    Dim lStart As Long : lStart = 1
    Dim result as String
    result = SF_String.FindRegex("abCcdefghHij", "C.*H", lStart, CaseSensitive := True)
    MsgBox lStart & ": " & result
    '3: CcdefghH
  
Ícone da dica

No exemplo acima, o novo valor de lStart pode ser utilizado para continuar a pesquisar a mesma cadeia de caracteres de entrada, definindo o parâmetro Start como lStart + Len(result) na iteração seguinte.


HashStr

As funções hash são utilizadas em alguns algoritmos criptográficos, em assinaturas digitais, códigos de autenticação de mensagens, deteção de manipulação, impressões digitais, somas de verificação (verificação da integridade das mensagens), tabelas hash, armazenamento de palavras-passe e muito mais.

O método HashStr devolve o resultado da aplicação de uma função hash a uma determinada cadeia de caracteres, utilizando um algoritmo especificado, sob a forma de uma cadeia de caracteres composta por dígitos hexadecimais em minúsculas.

Os algoritmos de hash suportados são: MD5, SHA1, SHA224, SHA256, SHA384 e SHA512.

Sintaxe:

svc.HashStr(inputstr: str, algorithm: str): str

Parâmetros:

inputstr: A cadeia de caracteres a ser submetida ao algoritmo de hash. Presume-se que esteja codificada em UTF-8. O algoritmo de hash considerará a cadeia de caracteres como um fluxo de bytes.

algoritmo: Um dos algoritmos suportados acima referidos, passado como uma cadeia de caracteres.

Exemplo:

Em Basic

    MsgBox SF_String.HashStr("œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬", "MD5")
    ' c740ccc2e201df4b2e2b4aa086f35d8a
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    a_string = "œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬"
    hash_value = svc.HashStr(a_string, "MD5")
    bas.MsgBox(hash_value)
    # c740ccc2e201df4b2e2b4aa086f35d8a
  

HtmlEncode

Codifica a cadeia de caracteres de entrada nos códigos de caracteres HTML, substituindo os caracteres especiais pelas suas equivalências &.

Por exemplo, o carácter é seria substituído por &eacute; ou por um código HTML numérico equivalente.

Sintaxe:

svc.HtmlEncode(inputstr: str): str

Parâmetros:

inputstr: A cadeia de caracteres a codificar.

Exemplo:


    MsgBox SF_String.HtmlEncode("<a href=""https://a.b.com"">From α to ω</a>")
    ' "&lt;a href=&quot;https://a.b.com&quot;&gt;From &#945; to &#969;&lt;/a&gt;"
  

IsADate

Devolve True se a cadeia de caracteres introduzida for uma data válida de acordo com um formato de data especificado.

Sintaxe:

svc.IsADate(inputstr: str, [dateformat: str]): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False

dateformat: O formato da data, expresso como uma cadeia de caracteres. Pode ser «AAAA-MM-DD» (padrão), «DD-MM-AAAA» ou «MM-DD-AAAA»

O traço (-) pode ser substituído por um ponto (.), uma barra (/) ou um espaço.

Se o formato for inválido, o método devolve False.

Exemplo:

Em Basic

    MsgBox SF_String.IsADate("2020-12-31", "YYYY-MM-DD") ' True
  
Ícone de nota

Este método verifica o formato da cadeia de caracteres introduzida sem efetuar quaisquer verificações específicas do calendário. Por conseguinte, não verifica se a cadeia de caracteres introduzida inclui anos bissextos ou meses com 30 ou 31 dias. Para esse efeito, consulte a função incorporada IsDate.


O exemplo abaixo mostra a diferença entre os métodos IsADate (ScriptForge) e a função IsDate (integrada).


    Dim myDate as String : myDate = "2020-02-30"
    MsgBox SF_String.IsADate(myDate, "YYYY-MM-DD") 'True
    MsgBox IsDate(myDate) ' False
  
Em Python

    svc = CreateScriptService("String")
    s_date = "2020-12-31"
    result = svc.IsADate(s_date) # True
  

IsAlpha

Devolve True se todos os caracteres da cadeia forem alfabéticos.

Os caracteres alfabéticos são aqueles definidos na Base de Dados de Caracteres Unicode como Letra.

Sintaxe:

svc.IsAlpha(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Exemplo:


    MsgBox SF_String.IsAlpha("àénΣlPµ") ' True
    MsgBox SF_String.IsAlpha("myVar3") ' False
  

IsAlphaNum

Devolve True se todos os caracteres da cadeia forem letras, algarismos ou «_» (traço inferior). O primeiro caractere não pode ser um algarismo.

Sintaxe:

svc.IsAlphaNum(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Exemplo:


    MsgBox SF_String.IsAlphaNum("_ABC_123456_abcàénΣlPµ") ' True
    MsgBox SF_String.IsAlphaNum("123ABC") ' False
  

IsAscii

Devolve True se todos os caracteres da cadeia forem caracteres ASCII.

Sintaxe:

svc.IsAscii(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Exemplo:


    MsgBox SF_String.IsAscii("a%?,25") ' True
    MsgBox SF_String.IsAscii("abcàénΣlPµ") ' False
  

IsDigit

Devolve True se todos os caracteres da cadeia forem dígitos.

Sintaxe:

svc.IsDigit(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Exemplo:


    MsgBox SF_String.IsDigit("123456") ' True
    MsgBox SF_String.IsDigit("_12a") ' False
  

IsEmail

Devolve True se a cadeia de caracteres for um endereço de e-mail válido.

Sintaxe:

svc.IsEmail(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Exemplo:

Em Basic

    MsgBox SF_String.IsEmail("first.last@something.org") ' True
    MsgBox SF_String.IsEmail("first.last@something.com.br") ' True
    MsgBox SF_String.IsEmail("first.last@something.123") ' False
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsEmail("first.last@something.org")) # True
    bas.MsgBox(svc.IsEmail("first.last@something.com.br")) # True
    bas.MsgBox(svc.IsEmail("first.last@something.123")) # False
  

IsFileName

Devolve True se a cadeia de caracteres for um nome de ficheiro válido num determinado sistema operativo.

Sintaxe:

svc.IsFileName(inputstr: str, [osname: str]): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

osname: O nome do sistema operativo, sob a forma de uma cadeia de caracteres. Pode ser «WINDOWS», «LINUX», «MACOSX» ou «SOLARIS».

O valor predefinido é o sistema operativo atual no qual o script está a ser executado.

Exemplo:

Em Basic

    MsgBox SF_String.IsFileName("/home/user/Documents/a file name.odt", "LINUX") ' True
    MsgBox SF_String.IsFileName("C:\home\a file name.odt", "LINUX") ' False
    MsgBox SF_String.IsFileName("C:\home\a file name.odt", "WINDOWS") ' True
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsFileName("/home/user/Documents/a file name.odt", "LINUX")) # True
    bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "LINUX")) # False
    bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "WINDOWS")) # True
  

IsHexDigit

Devolve True se todos os caracteres da cadeia forem dígitos hexadecimais.

Sintaxe:

svc.IsHexDigit(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Os dígitos hexadecimais podem ser precedidos por «0x» ou «&H».

Exemplo:


    MsgBox SF_String.IsHexDigit("&H00FF") ' True
    MsgBox SF_String.IsHexDigit("08AAFF10") ' True
    MsgBox SF_String.IsHexDigit("0x18LA22") ' False
  

IsIBAN

Devolve True se a cadeia de caracteres for um Número Internacional de Conta Bancária (IBAN) válido. A comparação não distingue maiúsculas de minúsculas.

Sintaxe:

svc.IsIBAN(inputstr: str): bool

Parâmetros:

inputstr: A cadeia de caracteres a verificar. Se estiver vazia, o método devolve False.

Tipo de retorno:

True se a cadeia de caracteres contiver um número IBAN válido.

Exemplo:


    ' Basic
    MsgBox SF_String.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") ' True
  

    # Python
    result = svc.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") # True
  

IsIPv4

Returns True if the string is a valid IP(v4) address.

Sintaxe:

svc.IsIPv4(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:

Em Basic

    MsgBox SF_String.IsIPv4("192.168.1.50") ' True
    MsgBox SF_String.IsIPv4("192.168.50") ' False
    MsgBox SF_String.IsIPv4("255.255.255.256") ' False
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsIPv4("192.168.1.50")) # True
    bas.MsgBox(svc.IsIPv4("192.168.50")) # False
    bas.MsgBox(svc.IsIPv4("255.255.255.256")) # False
  

IsLike

Returns True if the whole input string matches a given pattern containing wildcards.

Sintaxe:

svc.IsLike(inputstr: str, pattern: str, [casesensitive: bool]): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

pattern: The pattern as a string. Wildcards are:

casesensitive: The search can be case sensitive or not (Default = False).

Exemplo:

Em Basic

    MsgBox SF_String.IsLike("aAbB", "?A*") ' True
    MsgBox SF_String.IsLike("C:\a\b\c\f.odb", "?:*.*") ' True
    MsgBox SF_String.IsLike("name:host", "?*@?*") ' False
    MsgBox SF_String.IsLike("@host", "?*@?*") ' False
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsLike("aAbB", "?A*")) # True
    bas.MsgBox(svc.IsLike(r"C:\a\b\c\f.odb", "?:*.*")) # True
    bas.MsgBox(svc.IsLike("name:host", "?*@?*")) # False
    bas.MsgBox(svc.IsLike("@host", "?*@?*")) # False
  

IsLower

Returns True if all characters in the string are in lowercase. Non-alphabetic characters are ignored.

Sintaxe:

svc.IsLower(inputstr: str): bool

Parâmetros:

InputStr: The string to be checked. If empty, the method returns False.

Exemplo:


    MsgBox SF_String.IsLower("abc'(-xy4z") ' True
    MsgBox SF_String.IsLower("1234") ' True
    MsgBox SF_String.IsLower("abcDefg") ' False
  

IsPrintable

Returns True if all characters in the string are printable.

Sintaxe:

svc.IsPrintable(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:


    MsgBox SF_String.IsPrintable("àén ΣlPµ Русский") ' True
    MsgBox SF_String.IsPrintable("First line." & Chr(10) & "Second Line.") ' False
  

IsRegex

Returns True if the whole input string matches a given regular expression.

Sintaxe:

svc.IsRegex(inputstr: str, regex: str, [casesensitive: bool]): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

regex: The regular expression. If empty, the method returns False.

casesensitive: The search can be case sensitive or not (Default = False).

Exemplo:


        MsgBox SF_String.IsRegex("aAbB", "[A-Za-z]+") ' True
        MsgBox SF_String.IsRegex("John;100", "[A-Za-z]+;[0-9]+") ' True
        MsgBox SF_String.IsRegex("John;100;150", "[A-Za-z]+;[0-9]+") ' False
      

IsSheetName

Returns True if the input string is a valid Calc sheet name.

Sintaxe:

svc.IsSheetName(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:

Em Basic

    MsgBox SF_String.IsSheetName("1àbc + ""déf""") ' True
    MsgBox SF_String.IsSheetName("[MySheet]") ' False
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsSheetName("1àbc + ""déf""")) # True
    bas.MsgBox(svc.IsSheetName("[MySheet]")) # False
  
Ícone de nota

A sheet name must not contain the characters [ ] * ? : / \ or the character ' (apostrophe) as first or last character.


IsTitle

Returns True if the first character of every word is in uppercase and the other characters are in lowercase.

Sintaxe:

svc.IsTitle(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:


    MsgBox SF_String.IsTitle("This Is The Title Of My Book") ' True
    MsgBox SF_String.IsTitle("This is the Title of my Book") ' False
    MsgBox SF_String.IsTitle("Result Number 100") ' True
  

IsUpper

Returns True if all characters in the string are in uppercase. Non alphabetic characters are ignored.

Sintaxe:

svc.IsUpper(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:


    MsgBox SF_String.IsUpper("ABC'(-XYZ") ' True
    MsgBox SF_String.IsUpper("A Title") ' False
  

IsUrl

Returns True if the string is a valid absolute URL (Uniform Resource Locator) address. Only the http, https and ftp protocols are supported.

Sintaxe:

svc.IsUrl(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:

Em Basic

    MsgBox SF_String.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff") ' True
    MsgBox SF_String.IsUrl("www.somesite.org") ' False
  
Em Python

    svc = CreateScriptService("String")
    bas = CreateScriptService("Basic")
    bas.MsgBox(svc.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff")) # True
    bas.MsgBox(svc.IsUrl("www.somesite.org")) # False
  

IsWhitespace

Returns True if all characters in the string are whitespaces

Sintaxe:

svc.IsWhitespace(inputstr: str): bool

Parâmetros:

inputstr: The string to be checked. If empty, the method returns False.

Exemplo:


    MsgBox SF_String.IsWhitespace("    ") ' True
    MsgBox SF_String.IsWhitespace(" " & Chr(9) & Chr(10)) ' True
    MsgBox SF_String.IsWhitespace("") ' False
  

JustifyCenter

Returns the input string center-justified.

The leading and trailing white spaces are stripped and the remaining characters are completed left and right up to a specified total length with the character padding.

Sintaxe:

svc.JustifyCenter(inputstr: str, [length: int], [padding: str]): str

Parâmetros:

inputstr: The string to be center-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the center-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

Exemplo:


    MsgBox SF_String.JustifyCenter("Title", Length := 11) ' "   Title   "
    MsgBox SF_String.JustifyCenter("    ABCDEF", Padding := "_") ' "__ABCDEF__"
    MsgBox SF_String.JustifyCenter("A Long Title", Length := 5) ' "ong T"
  

JustifyLeft

Returns the input string left-justified.

The leading white spaces are stripped and the remaining characters are completed to the right up to a specified total length with the character padding.

Sintaxe:

svc.JustifyLeft(inputstr: str, [length: int], [padding: str]): str

Parâmetros:

inputstr: The string to be left-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the left-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

Exemplo:


    MsgBox SF_String.JustifyLeft("Title", Length := 10) ' "Title     "
    MsgBox SF_String.JustifyLeft("    ABCDEF", Padding := "_") ' "ABCDEF____"
    MsgBox SF_String.JustifyLeft("A Long Title", Length := 5) ' "A Lon"
  

JustifyRight

Returns the input string right-justified.

The leading white spaces are stripped and the remaining characters are completed to the left up to a specified total length with the character padding.

Sintaxe:

svc.JustifyRight(inputstr: str, [length: int], [padding: str]): str

Parâmetros:

inputstr: The string to be right-justified. If empty, the method returns an empty string.

length: The length of the resulting string (default = the length of the input string).

If the specified length is shorter than the right-justified input string, then the returned string is truncated.

padding: The single character to be used as padding (default = the ASCII space " ").

Exemplo:


    MsgBox SF_String.JustifyRight("Title", Length := 10) ' "     Title"
    MsgBox SF_String.JustifyRight("  ABCDEF  ", Padding := "_") ' "____ABCDEF"
    MsgBox SF_String.JustifyRight("A Long Title", Length := 5) ' "Title"
  

Quote

Returns the input string enclosed in single or double quotes. Existing quotes are left unchanged, including leading and/or trailing quotes.

Sintaxe:

svc.Quote(inputstr: str, [quotechar: str]): str

Parâmetros:

inputstr: The string to quote.

quotechar: Either the single (') or double (") quote (default).

Exemplo:


    MsgBox SF_String.Quote("Text Value")
    ' "Text Value"
    MsgBox SF_String.Quote("Book Title: ""The Arabian Nights""", "'")
    ' 'Book Title: "The Arabian Nights"'
  
Ícone da dica

This method can be useful while preparing a string field to be stored in a csv-like file, which requires that text values be enclosed with single or double quotes.


ReplaceChar

Replaces all occurrences of the characters specified in the Before parameter by the corresponding characters specified in After.

If the length of Before is greater than the length of After, the residual characters in Before are replaced by the last character in After.

Sintaxe:

svc.ReplaceChar(inputstr: str, before: str, after: str): str

Parâmetros:

inputstr: The input string on which replacements will occur.

before: A string with the characters that will be searched in the input string for replacement.

after: A string with the new characters that will replace those defined in before.

Exemplo:


    ' Replaces accented characters
    MsgBox SF_String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
    ' "Protegez votre vie privee"
    MsgBox SF_String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "")
    ' "Protgez votre vie prive"
    MsgBox SF_String.ReplaceChar("àâãçèéêëîïôöûüýÿ", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
    ' "aaaceeeeiioouuyy"
  

The SF_String service provides useful public constants for the Latin character sets, as shown in the example below:


    MsgBox SF_String.ReplaceChar("Protégez votre vie privée", SF_String.CHARSWITHACCENT, SF_String.CHARSWITHOUTACCENT)
    ' "Protegez votre vie privee"
  

ReplaceRegex

Replaces all occurrences of a given regular expression by a new string.

Sintaxe:

svc.ReplaceRegex(inputstr: str, regex: str, newstr: str, [casesensitive: bool]): str

Parâmetros:

inputstr: The input string on which replacements will occur.

regex: The regular expression.

newstr: The replacing string.

casesensitive: The search can be case sensitive or not (Default = False).

Exemplo:


    MsgBox SF_String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "[a-z]", "x", CaseSensitive := True)
    ' "Lxxxx xxxxx xxxxx xxx xxxx, xxxxxxxxxxx xxxxxxxxxx xxxx." (each lowercase letter is replaced by "x")
    MsgBox SF_String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", "x", CaseSensitive := False)
    ' "x x x x x, x x x." (each word is replaced by "x")
  

ReplaceStr

Replaces in a string some or all occurrences of an array of strings by an array of new strings.

Sintaxe:

svc.ReplaceStr(inputstr: str, oldstr: str, newstr: str, [occurrences: int], [casesensitive: bool]): str

Parâmetros:

inputstr: The input string on which replacements will occur.

oldstr: A single string or an array of strings. Zero-length strings are ignored.

newstr: The replacing string or the array of replacing strings.

If oldstr is an array, each occurrence of any of the items in oldstr is replaced by newstr.

If oldstr and newstr are arrays, replacements occur one by one up to the UBound(newstr).

If oldstr has more entries than newstr, then the residual elements in oldstr are replaced by the last element in newstr.

occurrences: The maximum number of replacements. The default value is 0, meaning that all occurrences will be replaced.

When oldstr is an array, the occurrence parameter is computed separately for each item in the array.

casesensitive: The search can be case sensitive or not (Default = False).

Exemplo:


    MsgBox SF_String.ReplaceStr("100 xxx 200 yyy", Array("xxx", "yyy"), Array("(1)", "(2)"), CaseSensitive := False)
    ' "100 (1) 200 (2)"
    MsgBox SF_String.ReplaceStr("abCcdefghHij", Array("c", "h"), Array("Y", "Z"), CaseSensitive := False)
    ' "abYYdefgZZij"
  

Represent

Returns a string with a readable representation of the argument, truncated at a given length. This is useful mainly for debugging or logging purposes.

If the anyvalue parameter is an object, it will be enclosed with square brackets "[" and "]".

In strings, tabs and line breaks are replaced by \t, \n or \r.

If the final length exceeds the maxlength parameter, the latter part of the string is replaced by " ... (N)" where N is the total length of the original string before truncation.

Sintaxe:

svc.Represent(anyvalue: any, [maxlength: int]): str

Parâmetros:

anyvalue: The input value to be represented. It can be any value, such as a string, an array, a Basic object, a UNO object, etc.

maxlength: The maximum length of the resulting string. The default value is 0, meaning there is no limit to the length of the resulting representation.

Exemplo:


    MsgBox SF_String.Represent("this is a usual string") ' "this is a usual string"
    MsgBox SF_String.Represent("this is a usual string", 15) ' "this i ... (22)"
    MsgBox SF_String.Represent("this is a" & Chr(10) & " 2-lines string") ' "this is a\n 2-lines string"
    MsgBox SF_String.Represent(Empty) ' "[EMPTY]"
    MsgBox SF_String.Represent(Null) ' "[NULL]"
    MsgBox SF_String.Represent(Pi) ' "3.142"
    MsgBox SF_String.Represent(CreateUnoService("com.sun.star.util.PathSettings")) ' "[com.sun.star.comp.framework.PathSettings]"
  

Note that the representation of data types such as Arrays and ScriptForge.Dictionary object instances include both the data type and their values:


    ' An example with a Basic built-in Array
    MsgBox SF_String.Represent(Array(1, 2, "Text" & Chr(9) & "here"))
    ' "[ARRAY] (0:2) (1, 2, Text\there)"
    ' An example with a ScriptForge Array
    Dim aValues as Variant
    aValues = SF_Array.RangeInit(1, 5)
    MsgBox SF_String.Represent(aValues)
    ' "[ARRAY] (0:4) (1.0, 2.0, 3.0, 4.0, 5.0)"
    ' An example with a ScriptForge Dictionary
    Dim myDict As Variant : myDict = CreateScriptService("Dictionary")
    myDict.Add("A", 1) : myDict.Add("B", 2)
    MsgBox SF_String.Represent(myDict)
    ' "[Dictionary] ("A":1, "B":2)"
  

Reverse

Returns the input string in reversed order.

This method is equivalent to the built-in StrReverse Basic function.

Ícone de nota

To use the StrReverse function, the statement Option VBASupport 1 must be present in the module.


Sintaxe:

svc.Reverse(inputstr: str): str

Parâmetros:

inputstr: The string to be reversed.

Exemplo:


    MsgBox SF_String.Reverse("abcdefghij") ' "jihgfedcba"
  

SplitLines

Returns a zero-based array of strings with the lines in the input string. Each item in the array is obtained by splitting the input string at newline characters.

Sintaxe:

svc.SplitLines(inputstr: str, [keepbreaks: int]): str[0..*]

Parâmetros:

inputstr: The string to be split.

keepbreaks: When True, line breaks are preserved in the output array (default = False).

Exemplo:


    Dim a as Variant
    a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3")
    ' a = Array("Line1", "Line2", "Line3")
    a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10))
    ' a = Array("Line1", "Line2", "Line3", "")
    a = SF_String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10), KeepBreaks := True)
    ' a = Array("Line1\n", "Line2\r", "Line3\n", "")
  

SplitNotQuoted

Splits a string into an array of elements using a specified delimiter.

If a quoted substring contains a delimiter, it is ignored. This is useful when parsing CSV-like records that contain quoted strings.

Sintaxe:

svc.SplitNotQuoted(inputstr: str, [delimiter: str], [occurrences: int], [quotechar: str]): str[0..*]

Parâmetros:

inputstr: The string to be split.

delimiter: A string of one or more characters that will be used as delimiter. The default delimiter is the ASCII space " " character.

occurrences: The maximum number of substrings to return. The default value is 0, meaning that there is no limit to the number of returned strings.

quotechar: Either the single (') or double (") quote.

Exemplo:

Em Basic

    arr1 = SF_String.SplitNotQuoted("abc def ghi")
    ' arr1 = Array("abc", "def", "ghi")
    arr2 = SF_String.SplitNotQuoted("abc,""def,ghi""", ",")
    ' arr2 = Array("abc", """def,ghi""")
    arr3 = SF_String.SplitNotQuoted("abc,""def\"",ghi""", ",")
     ' arr3 = Array("abc", """def\"",ghi""")
    arr4 = SF_String.SplitNotQuoted("abc,""def\"",ghi"""",", ",")
    ' arr4 = Array("abc", """def\"",ghi""", "")
  
Em Python

    svc = CreateScriptService("String")
    arr1 = svc.SplitNotQuoted('abc def ghi')
    # arr1 = ('abc', 'def', 'ghi')
    arr2 = svc.SplitNotQuoted('abc,"def,ghi"', ",")
    # arr2 = ('abc', '"def,ghi"')
    arr3 = svc.SplitNotQuoted(r'abc,"def\",ghi"', ",")
    # arr3 = ('abc', '"def\\",ghi"')
    arr4 = svc.SplitNotQuoted(r'abc,"def\",ghi"",', ",")
    # arr4 = ('abc', '"def\\",ghi""', '')
  
Ícone de nota

Beware of the differences between Basic and Python when representing strings. For example, in Basic two "" characters inside a string are interpreted as a single " character. In Python, strings enclosed with single quotes can contain " characters without having to double them.


StartsWith

Returns True if the first characters of a string are identical to a given substring.

This method returns False if either the input string or the substring have a length = 0 or when the substring is longer than the input string.

Sintaxe:

svc.StartsWith(inputstr: str, substring: str, [casesensitive: bool]): bool

Parâmetros:

inputstr: The string to be tested.

substring: The substring to be searched at the start of inputstr.

casesensitive: The search can be case sensitive or not (Default = False).

Exemplo:


    MsgBox SF_String.StartsWith("abcdefg", "ABC") 'True
    MsgBox SF_String.StartsWith("abcdefg", "ABC", CaseSensitive := True) 'False
  

TrimExt

Returns the input string without its leading and trailing whitespaces.

Sintaxe:

svc.TrimExt(inputstr: str): str

Parâmetros:

inputstr: The string to trim.

Exemplo:


    MsgBox SF_String.TrimExt(" Some text.  ") ' "Some text."
    MsgBox SF_String.TrimExt("   ABCDEF" & Chr(9) & Chr(10) & Chr(13) & " ") ' "ABCDEF"
  

Unescape

Converts any escaped sequence (\\, \n, \r, \t) in the input string to their corresponding ASCII character.

Sintaxe:

svc.Unescape(inputstr: str): str

Parâmetros:

inputstr: The string to be converted.

Exemplo:


    MsgBox SF_String.Unescape("abc\n\tdef\\n")
    ' "abc" & Chr(10) & Chr(9) & "def\n"
  

Unquote

Removes the single or double quotes enclosing the input string.

This is useful when parsing CSV-like records that contain quoted strings.

Sintaxe:

svc.Unquote(inputstr: str, [quotechar: str]): str

Parâmetros:

inputstr: The string to unquote.

quotechar: Either the single (') or double (") quote (default).

Exemplo:


    Dim s as String
    ' s = "Some text" (without enclosing quotes)
    s = SF_String.Unquote("""Some text""")
    ' The string below does not have enclosing quotes, so it remains unchanged
    ' s = "Some text" (unchanged)
    s = SF_String.Unquote("Some text")
    ' Quotes inside the string are not removed
    ' s = "The ""true"" meaning" (unchanged)
    s = SF_String.Unquote("The ""true"" meaning")
  

Wrap

Converts the input string into an array of substrings so that each item in the array has at most a given number of characters.

In practice, this method returns a zero-based array of output lines, without newlines at the end, except for the pre-existing line-breaks.

Tabs are expanded using the same procedure performed by the ExpandTabs method.

Symbolic line breaks are replaced by their equivalent ASCII characters.

If the wrapped output has no content, the returned array is empty.

Sintaxe:

svc.Wrap(inputstr: str, [width: int], [tabsize: int]): str

Parâmetros:

inputstr: The string to wrap.

width: The maximum number of characters in each line (Default = 70).

tabsize: Before wrapping the text, the existing TAB Chr(9) characters are replaced with spaces. The argument tabsize defines the TAB stops at TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1 (Default = 8).

Exemplo:

Em Basic

    a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
    b = SF_String.Wrap(a, 20)
    ' Array("Neque porro ", "quisquam est qui ", "dolorem ipsum quia ", "dolor sit amet, ", "consectetur, ", "adipisci velit...")
  
Em Python

    a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
    b = svc.Wrap(a, 20)
    # ('Neque porro ', 'quisquam est qui ', 'dolorem ipsum quia ', 'dolor sit amet, ', 'consectetur, ', 'adipisci velit...')
  
Ícone de aviso

Todas as rotinas ou identificadores do ScriptForge Basic que tenham o caractere de sublinhado «_» como prefixo estão reservados para uso interno. Não se destinam a ser utilizados em macros do Basic ou em scripts Python.


Necessitamos da sua ajuda!

Necessitamos da sua ajuda!