Difference between revisions of "IDE regular expressions/pl"

From Lazarus wiki
Jump to navigationJump to search
(tłumaczenie na j. polski)
(→‎Regexpr by Sorokin: tłumaczenie na j. polski)
Line 3: Line 3:
 
Pakiet RegExpr zawiera wiele implementacji wyrażeń regularnych
 
Pakiet RegExpr zawiera wiele implementacji wyrażeń regularnych
  
==Regexpr by Sorokin==
+
==Regexpr wg Sorokina==
  
 
Jest to najbardziej kompletna implementacja dostępna w packages/regexpr/src/regexpr.pas
 
Jest to najbardziej kompletna implementacja dostępna w packages/regexpr/src/regexpr.pas
Line 11: Line 11:
 
Ten pakiet implementuje podzbiór wyrażeń regularnych Perla, a składnia dostarczona przez pakiet jest udokumentowana tutaj: https://regex.sorokin.engineer/regex
 
Ten pakiet implementuje podzbiór wyrażeń regularnych Perla, a składnia dostarczona przez pakiet jest udokumentowana tutaj: https://regex.sorokin.engineer/regex
  
===Change case on replaces===
+
===Zmiana wielkość liter w trakcie zastępowania===
  
You can change case of found fragments, use modifiers in replace-with field (case change works after position of modifier):
+
Możesz zmienić wielkość liter w znalezionych fragmentach, użyć modyfikatorów w polu zamień na (zmiana wielkości liter działa po pozycji modyfikatora):
  
* \l - First char to lower
+
* \l - Pierwszy znak na małą literę
* \L - All chars to lower
+
* \L - Wszystkie znaki na małe litery
* \u - First char to upper
+
* \u - Pierwszy znak na wielką literę
* \U - All chars to upper
+
* \U - Wszystkie znaki na wielkie litery
  
E.g. if found a word, use replace-with field "\L$0" to change word to lowercase (here $0 is group 0, found text).
+
Np. jeśli znaleziono słowo, to użyj wyrażenie zastępowania „\L$0”, aby zmienić słowo na małe litery (tutaj 0$ jest grupą 0 znalezionego tekstu).
  
In addition \n will be replaced with the LineEnd character (or character sequence).
+
Ponadto \n zostanie zastąpiony znakiem końca wiersza (lub sekwencją znaków).
  
===Simple usage example===
+
===Prosty przykład użycia===
  
Using Sorokin RegExpr to check if an expression is present in a string is very easy, just create an instance of TRegExpr, then place your regular expression in the property TRegExpr.Expression and use the method Exec to verify if there are any matches for this regular expression. Exec will return true if the expression matches the string passed to it.
+
Użycie RegExpr Sorokina do sprawdzenia, czy wyrażenie jest obecne w ciągu jest bardzo łatwe, po prostu utwórz instancję TRegExpr, a następnie umieść swoje wyrażenie regularne we właściwości TRegExpr.Expression, a następnie użyj metody Exec, aby sprawdzić, czy są jakieś dopasowania dla tego regularnego wyrażenie. Exec zwróci wartość '''true''', jeśli wyrażenie pasuje do przekazanego mu ciągu.
  
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">
Line 34: Line 34:
 
   RegexObj := TRegExpr.Create;
 
   RegexObj := TRegExpr.Create;
 
   RegexObj.Expression := '.*login.*';
 
   RegexObj.Expression := '.*login.*';
   if RegexObj.Exec('Please try to login here') then WriteLn('The login was found!');
+
   if RegexObj.Exec('Spróbuj zalogować się tutaj') then WriteLn('Login został znaleziony!');
 
   RegexObj.Free;
 
   RegexObj.Free;
 
end;
 
end;
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Subexpression match:
+
Dopasowanie podwyrażenia:
  
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">
Line 50: Line 50:
 
   re: TRegExpr;
 
   re: TRegExpr;
 
begin
 
begin
   re := TRegExpr.Create('hello (.*?)!');
+
   re := TRegExpr.Create('witaj (.*?)!');
   if re.Exec('hello world! hello pascal!') then
+
   if re.Exec('witaj świecie! witaj pascal!') then
 
   begin
 
   begin
 
     WriteLn(re.Match[1]);
 
     WriteLn(re.Match[1]);
Line 63: Line 63:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Output:
+
Wynik:
  
 
<pre>
 
<pre>
world
+
świecie
 
pascal
 
pascal
 
</pre>
 
</pre>

Revision as of 18:38, 27 June 2020

Template:Regexpr

Pakiet RegExpr zawiera wiele implementacji wyrażeń regularnych

Regexpr wg Sorokina

Jest to najbardziej kompletna implementacja dostępna w packages/regexpr/src/regexpr.pas

Przeczytaj stronę wikipedii o wyrażeniach regularnych, aby zapoznać się z tym tematem: Podstawowe wyrażenia regularne POSIX

Ten pakiet implementuje podzbiór wyrażeń regularnych Perla, a składnia dostarczona przez pakiet jest udokumentowana tutaj: https://regex.sorokin.engineer/regex

Zmiana wielkość liter w trakcie zastępowania

Możesz zmienić wielkość liter w znalezionych fragmentach, użyć modyfikatorów w polu zamień na (zmiana wielkości liter działa po pozycji modyfikatora):

  • \l - Pierwszy znak na małą literę
  • \L - Wszystkie znaki na małe litery
  • \u - Pierwszy znak na wielką literę
  • \U - Wszystkie znaki na wielkie litery

Np. jeśli znaleziono słowo, to użyj wyrażenie zastępowania „\L$0”, aby zmienić słowo na małe litery (tutaj 0$ jest grupą 0 znalezionego tekstu).

Ponadto \n zostanie zastąpiony znakiem końca wiersza (lub sekwencją znaków).

Prosty przykład użycia

Użycie RegExpr Sorokina do sprawdzenia, czy wyrażenie jest obecne w ciągu jest bardzo łatwe, po prostu utwórz instancję TRegExpr, a następnie umieść swoje wyrażenie regularne we właściwości TRegExpr.Expression, a następnie użyj metody Exec, aby sprawdzić, czy są jakieś dopasowania dla tego regularnego wyrażenie. Exec zwróci wartość true, jeśli wyrażenie pasuje do przekazanego mu ciągu.

var
  RegexObj: TRegExpr;
begin
  RegexObj := TRegExpr.Create;
  RegexObj.Expression := '.*login.*';
  if RegexObj.Exec('Spróbuj zalogować się tutaj') then WriteLn('Login został znaleziony!');
  RegexObj.Free;
end;

Dopasowanie podwyrażenia:

program Project1;

uses
  RegExpr;

var
  re: TRegExpr;
begin
  re := TRegExpr.Create('witaj (.*?)!');
  if re.Exec('witaj świecie! witaj pascal!') then
  begin
    WriteLn(re.Match[1]);
    while re.ExecNext do
    begin
      WriteLn(re.Match[1]);
    end;
  end;
  re.Free;
end.

Wynik:

świecie
pascal

FLRE - Fast Light Regular Expressions by BeRo1985

FLRE (F ast L ight R egular E xpressions) is a fast, safe and efficient regular expression library, which is implemented in Object Pascal (Delphi and Free Pascal) but which is even usable from other languages like C/C++ and so on. Can handle Unicode and UTF8 strings.

It implements the many of the most common Perl and POSIX features, except irregular expression features like forward references and nested back references and so on, which aren't supported at FLRE, only real "back" references are supported, hence also the word "Light" at the FLRE name. It also finds the leftmost-first match, the same match that Perl and PCRE would, and can return submatch information. But it also features a flag for a yet experimental POSIX-style leftmost-longest match behaviour mode.

FLRE is licensed under the LGPL v2.1 with static-linking-exception.

Github repository

Example

Implementing PHP parse_url function (based on php.js parse_url implementation)

uses Classes, SysUtils, flre;

type

    RUrlParser = record
private
    Fcomponents                 : array[1..13] of string;

private
    function    getComponent( aIndex : integer ) : string;
    procedure   setComponent( aIndex : integer; const aValue : string );

public
    function    parse( const aUrl : UTF8String ) : boolean;

public
    property scheme : string index 1 read getComponent write setComponent; // e.g. http
    property authority : string index 2 read getComponent;
    property userInfo : string index 3 read getComponent;
    property user : string index 4 read getComponent;
    property pass : string index 5 read getComponent;
    property host : string index 6 read getComponent;
    property port : string index 7 read getComponent;
    property path : string index 9 read getComponent;
    property directory : string index 10 read getComponent;
    property fileName : string index 11 read getComponent;
    property query : string  index 12 read getComponent; // after the question mark ?
    property fragment : string  index 13 read getComponent; // after the hashmark #

    end;

implementation

function RUrlParser.getComponent( aIndex : integer ) : string;
begin
    Result := Fcomponents[ aIndex ];
end;

procedure RUrlParser.setComponent( aIndex : integer; const aValue : string );
begin
    Fcomponents[ aIndex ] := aValue;
end;

function RUrlParser.parse( const aUrl : UTF8String ) : boolean; overload;
var
    i : integer;
    re : TFLRE;
    parts : TFLREMultiStrings;
begin
    re := TFLRE.Create( '(?:([^:\\/\?#]+):)?'
        + '(?:\/\/()(?:(?:()(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?'
        + '()'
        + '(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)'
        , [ rfUTF8 ]
    ); 

    parts := nil;
    Result := re.UTF8ExtractAll( aUrl, parts );
    if ( Result ) then
    begin
        for i := 1 to Length( parts[0] ) - 1 do
        begin
            setComponent( i, string( parts[0][i] ) );
        end;
    end;

    // Free regexp memory
    for i := 0 to Length( parts ) - 1 do
    begin
        SetLength( parts[i], 0 );
    end;
    parts := nil;

    re.Free();
end;

Regexpr by Joost

Regexpr by Joost (units oldregexpr.pp and regex.pp) is a very basic regex (Regular Expression) unit, it handles most regular expressions as GNU regexpr. The use of regex is to search patterns inside a string.

The current unit is far from complete, and still misses very simple syntax support of POSIX or more complex syntax such as Perl regex, Java Regex, Ruby Regex etc...

The unit contains 4 functions for now:

  • GenerateRegExprEngine – This function compiles the regex pattern.
  • RegExprPos – Finds the pattern inside a given string.
  • DestroyRegExprEngine – Free the compilation of the pattern
  • RegExprEscapeStr – Escape reserve syntax of regular expression language so it will be understood as string instead of regex syntax.

There is also one test:

  • The testreg1 test program demonstrates the supported regular expressions.

Regexpr by Florian

This is the oldest implementation. It is present in packages/regexpr/src/old and is not currently compiled by the makefiles, so it is not available precompiled by default in released FPC/Lazarus versions.

See Also

Go to back Packages List