Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- Regular expressions
from: http://rosettacode.org/wiki/Regular_expressions
note: Text processing

View file

@ -0,0 +1,5 @@
;Task:
:*   match a string against a regular expression
:*   substitute part of a string using a regular expression
<br><br>

View file

@ -0,0 +1,7 @@
V string = This is a string
I re:string$.search(string)
print(Ends with string.)
string = string.replace(re: a , another )
print(string)

View file

@ -0,0 +1,2 @@
"haystack" /a./ r:match . cr
"haystack" /a./ "blah" s:replace! . cr

View file

@ -0,0 +1,11 @@
DATA: text TYPE string VALUE 'This is a Test'.
FIND FIRST OCCURRENCE OF REGEX 'is' IN text.
IF sy-subrc = 0.
cl_demo_output=>write( 'Regex matched' ).
ENDIF.
REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'.
cl_demo_output=>write( text ).
cl_demo_output=>display( ).

View file

@ -0,0 +1,13 @@
INT match=0, no match=1, out of memory error=2, other error=3;
STRING str := "i am a string";
# Match: #
STRING m := "string$";
INT start, end;
IF grep in string(m, str, start, end) = match THEN printf(($"Ends with """g""""l$, str[start:end])) FI;
# Replace: #
IF sub in string(" a ", " another ",str) = match THEN printf(($gl$, str)) FI;

View file

@ -0,0 +1,12 @@
FORMAT pattern = $ddd" "c("cats","dogs")$;
FILE file; STRING book; associate(file, book);
on value error(file, (REF FILE f)BOOL: stop);
on format error(file, (REF FILE f)BOOL: stop);
book := "100 dogs";
STRUCT(INT count, type) dalmatians;
getf(file, (pattern, dalmatians));
print(("Dalmatians: ", dalmatians, new line));
count OF dalmatians +:=1;
printf(($"Gives: "$, pattern, dalmatians, $l$))

View file

@ -0,0 +1,4 @@
$ awk '{if($0~/[A-Z]/)print "uppercase detected"}'
abc
ABC
uppercase detected

View file

@ -0,0 +1,4 @@
awk '/[A-Z]/{print "uppercase detected"}'
def
DeF
uppercase detected

View file

@ -0,0 +1,6 @@
$ awk '{gsub(/[A-Z]/,"*");print}'
abCDefG
ab**ef*
$ awk '{gsub(/[A-Z]/,"(&)");print}'
abCDefGH
ab(C)(D)ef(G)(H)

View file

@ -0,0 +1,3 @@
$ awk '{gsub(/[A-Z]+/,"(&)");print}'
abCDefGH
ab(CD)ef(GH)

View file

@ -0,0 +1,43 @@
with Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;
procedure Regex is
package Pat renames Gnat.Regpat;
procedure Search_For_Pattern(Compiled_Expression: Pat.Pattern_Matcher;
Search_In: String;
First, Last: out Positive;
Found: out Boolean) is
Result: Pat.Match_Array (0 .. 1);
begin
Pat.Match(Compiled_Expression, Search_In, Result);
Found := not Pat."="(Result(1), Pat.No_Match);
if Found then
First := Result(1).First;
Last := Result(1).Last;
end if;
end Search_For_Pattern;
Word_Pattern: constant String := "([a-zA-Z]+)";
Str: String:= "I love PATTERN matching!";
Current_First: Positive := Str'First;
First, Last: Positive;
Found: Boolean;
begin
-- first, find all the words in Str
loop
Search_For_Pattern(Pat.Compile(Word_Pattern),
Str(Current_First .. Str'Last),
First, Last, Found);
exit when not Found;
Put_Line("<" & Str(First .. Last) & ">");
Current_First := Last+1;
end loop;
-- second, replace "PATTERN" in Str by "pattern"
Search_For_Pattern(Pat.Compile("(PATTERN)"), Str, First, Last, Found);
Str := Str(Str'First .. First-1) & "pattern" & Str(Last+1 .. Str'Last);
Put_Line(Str);
end Regex;

View file

@ -0,0 +1,14 @@
#include <hopper.h>
main:
expReg="[A-Z]{1,2}[0-9][0-9A-Z]? +[0-9][A-Z]{2}"
flag compile = REG_EXTENDED
flag match=0
número de matches=10, T1=0
{flag compile,expReg} reg compile(T1) // compile regular expression, pointed whit T1
{flag match,número de matches,T1,"We are at SN12 7NY for this course"},reg match, // execute
println
reg free(T1) // free pointer to regular expression compiled.
exit(0)

View file

@ -0,0 +1,28 @@
#include <hopper.h>
main:
expReg="[A-Z]{1,2}[0-9][0-9A-Z]? +[0-9][A-Z]{2}"
cadena = "We are at SN12 7NY for this course"
flag compile = REG_EXTENDED
flag match=0
número de matches=10, T1=0
{flag compile,expReg} reg compile(T1) // compile regular expression, pointed whit T1
{flag match,número de matches,T1,cadena},reg match, // execute
matches=0,mov(matches)
reg free(T1) // free pointer to regular expression compiled.
From=0, To=0, toSearch=""
[1,1]get(matches), mov(From)
[1,2]get(matches), mov(To)
[1,3]get(matches), mov(toSearch)
// substitute with "transform":
{"another thing",toSearch,cadena}transform, println
// substitute with "delete"/"insert":
{To}minus(From),plus(1), {From, cadena} delete, mov(cadena)
{From,"another thing",cadena}insert , println
exit(0)

View file

@ -0,0 +1,11 @@
try
find text ".*string$" in "I am a string" with regexp
on error message
return message
end try
try
change "original" into "modified" in "I am the original string" with regexp
on error message
return message
end try

View file

@ -0,0 +1,9 @@
-- Get the run of non-white-space at the end, if any.
try
set output to (do shell script "echo 'I am a string' | egrep -o '\\S+$'")
on error message
set output to "No match"
end try
-- Replace the first instance of "orig…" with "modified".
set moreOutput to(do shell script "echo 'I am the original string' | sed 's/orig[a-z]*/modified/'")
return output & linefeed & moreOutput

View file

@ -0,0 +1,24 @@
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
-- Get the run of non-white-space at the end, if any.
set aString to current application's class "NSString"'s stringWithString:("I am a string")
set matchRange to aString's rangeOfString:("\\S++$") ¬
options:(current application's NSRegularExpressionSearch) range:({0, aString's |length|()})
if (matchRange's |length|() > 0) then
set output to aString's substringWithRange:(matchRange)
else
set output to "No match"
end if
-- Replace the first instance of "orig…" with "modified".
set anotherString to current application's class "NSString"'s stringWithString:("I am the original string")
set matchRange2 to anotherString's rangeOfString:("orig[a-z]*+") ¬
options:(current application's NSRegularExpressionSearch) range:({0, anotherString's |length|()})
if (matchRange2's |length|() > 0) then
set moreOutput to anotherString's stringByReplacingCharactersInRange:(matchRange2) withString:("modified")
else
set moreOutput to anotherString
end if
return (output as text) & linefeed & moreOutput

View file

@ -0,0 +1,24 @@
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
-- Get the run of non-white-space at the end, if any.
set aString to current application's class "NSString"'s stringWithString:("I am a string")
set aRegex to current application's class "NSRegularExpression"'s regularExpressionWithPattern:("\\S++$") options:(0) |error|:(missing value)
set matchRange to aRegex's rangeOfFirstMatchInString:(aString) options:(0) range:({0, aString's |length|()})
if (matchRange's |length|() > 0) then
set output to aString's substringWithRange:(matchRange)
else
set output to "No match"
end if
-- Replace the first instance of "orig…" with "modified".
set anotherString to current application's class "NSString"'s stringWithString:("I am the original string")
set anotherRegex to current application's class "NSRegularExpression"'s regularExpressionWithPattern:("orig[a-z]*+") options:(0) |error|:(missing value)
set matchRange2 to anotherRegex's rangeOfFirstMatchInString:(anotherString) options:(0) range:({0, anotherString's |length|()})
if (matchRange2's |length|() > 0) then
set moreOutput to anotherString's stringByReplacingCharactersInRange:(matchRange2) withString:("modified")
else
set moreOutput to anotherString
end if
return (output as text) & linefeed & moreOutput

View file

@ -0,0 +1,22 @@
use std, regex
(: matching :)
if "some matchable string" =~ /^some" "+[a-z]*" "+string$/
echo string matches
else
echo string "doesn't" match
(: replacing :)
let t = strdup "some allocated string"
t =~ s/a/"4"/g
t =~ s/e/"3"/g
t =~ s/i/"1"/g
t =~ s/o/"0"/g
t =~ s/s/$/g
print t
free t
(: flushing regex allocations :)
uninit regex
check mem leak; use dbg (:optional:)

View file

@ -0,0 +1,7 @@
s: "This is a string"
if contains? s {/string$/} -> print "yes, it ends with 'string'"
replace 's {/[as]/} "x"
print s

View file

@ -0,0 +1,2 @@
MsgBox % foundpos := RegExMatch("Hello World", "World$")
MsgBox % replaced := RegExReplace("Hello World", "World$", "yourself")

View file

@ -0,0 +1,40 @@
SYS "LoadLibrary", "gnu_regex.dll" TO gnu_regex%
IF gnu_regex% = 0 ERROR 100, "Cannot load gnu_regex.dll"
SYS "GetProcAddress", gnu_regex%, "regcomp" TO regcomp
SYS "GetProcAddress", gnu_regex%, "regexec" TO regexec
DIM regmatch{start%, finish%}, buffer% 256
REM Find all 'words' in a string:
teststr$ = "I love PATTERN matching!"
pattern$ = "([a-zA-Z]+)"
SYS regcomp, buffer%, pattern$, 1 TO result%
IF result% ERROR 101, "Failed to compile regular expression"
first% = 1
REPEAT
SYS regexec, buffer%, MID$(teststr$, first%), 1, regmatch{}, 0 TO result%
IF result% = 0 THEN
s% = regmatch.start%
f% = regmatch.finish%
PRINT "<" MID$(teststr$, first%+s%, f%-s%) ">"
first% += f%
ENDIF
UNTIL result%
REM Replace 'PATTERN' with 'pattern':
teststr$ = "I love PATTERN matching!"
pattern$ = "(PATTERN)"
SYS regcomp, buffer%, pattern$, 1 TO result%
IF result% ERROR 101, "Failed to compile regular expression"
SYS regexec, buffer%, teststr$, 1, regmatch{}, 0 TO result%
IF result% = 0 THEN
s% = regmatch.start%
f% = regmatch.finish%
MID$(teststr$, s%+1, f%-s%) = "pattern"
PRINT teststr$
ENDIF
SYS "FreeLibrary", gnu_regex%

View file

@ -0,0 +1 @@
@("fesylk789/35768poq2art":? (#<7:?n & out$!n & ~) ?)

View file

@ -0,0 +1,7 @@
str = "I am a string"
true? str.match(/string$/)
{ p "Ends with 'string'" }
false? str.match(/^You/)
{ p "Does not start with 'You'" }

View file

@ -0,0 +1,19 @@
# Substitute in copy
str2 = str.sub(/ a /, " another ")
p str # original unchanged
p str2 # prints "I am another string"
# Substitute in place
str.sub!(/ a /, " another ")
p str # prints "I am another string"
# Substitute with a block
str.sub! /a/
{ match | match.upcase }
p str # prints "I Am Another string"

View file

@ -0,0 +1,39 @@
#include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
// match the complete string
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
// match a substring
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
// replace a substring
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}

View file

@ -0,0 +1,15 @@
using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
Console.WriteLine(str);
}
}

View file

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
int main()
{
regex_t preg;
regmatch_t substmatch[1];
const char *tp = "string$";
const char *t1 = "this is a matching string";
const char *t2 = "this is not a matching string!";
const char *ss = "istyfied";
regcomp(&preg, "string$", REG_EXTENDED);
printf("'%s' %smatched with '%s'\n", t1,
(regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
printf("'%s' %smatched with '%s'\n", t2,
(regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
regfree(&preg);
/* change "a[a-z]+" into "istifyed"?*/
regcomp(&preg, "a[a-z]+", REG_EXTENDED);
if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
{
//fprintf(stderr, "%d, %d\n", substmatch[0].rm_so, substmatch[0].rm_eo);
char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
(strlen(t1) - substmatch[0].rm_eo) + 2);
memcpy(ns, t1, substmatch[0].rm_so+1);
memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
strlen(&t1[substmatch[0].rm_eo]));
ns[ substmatch[0].rm_so + strlen(ss) +
strlen(&t1[substmatch[0].rm_eo]) ] = 0;
printf("mod string: '%s'\n", ns);
free(ns);
} else {
printf("the string '%s' is the same: no matching!\n", t1);
}
regfree(&preg);
return 0;
}

View file

@ -0,0 +1,54 @@
#include <stdio.h>
#include <glib.h>
void print_regex_match(const GRegex* regex, const char* string) {
GMatchInfo* match_info;
gboolean match = g_regex_match(regex, string, 0, &match_info);
printf(" string = '%s': %s\n", string, match ? "yes" : "no");
g_match_info_free(match_info);
}
void regex_match_demo() {
const char* pattern = "^[a-z]+$";
GError* error = NULL;
GRegex* regex = g_regex_new(pattern, 0, 0, &error);
if (regex == NULL) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return;
}
printf("Does the string match the pattern '%s'?\n", pattern);
print_regex_match(regex, "test");
print_regex_match(regex, "Test");
g_regex_unref(regex);
}
void regex_replace_demo() {
const char* pattern = "[0-9]";
const char* input = "Test2";
const char* replace = "X";
GError* error = NULL;
GRegex* regex = g_regex_new(pattern, 0, 0, &error);
if (regex == NULL) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return;
}
char* result = g_regex_replace_literal(regex, input, -1,
0, replace, 0, &error);
if (result == NULL) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
} else {
printf("Replace pattern '%s' in string '%s' by '%s': '%s'\n",
pattern, input, replace, result);
g_free(result);
}
g_regex_unref(regex);
}
int main() {
regex_match_demo();
regex_replace_demo();
return 0;
}

View file

@ -0,0 +1,10 @@
(let [s "I am a string"]
;; match
(when (re-find #"string$" s)
(println "Ends with 'string'."))
(when-not (re-find #"^You" s)
(println "Does not start with 'You'."))
;; substitute
(println (clojure.string/replace s " a " " another "))
)

View file

@ -0,0 +1,5 @@
(let ((string "I am a string"))
(when (cl-ppcre:scan "string$" string)
(write-line "Ends with string"))
(unless (cl-ppcre:scan "^You" string )
(write-line "Does not start with 'You'")))

View file

@ -0,0 +1,3 @@
(let* ((string "I am a string")
(string (cl-ppcre:regex-replace " a " string " another ")))
(write-line string))

View file

@ -0,0 +1,5 @@
(let ((string "I am a string"))
(multiple-value-bind (string matchp)
(cl-ppcre:regex-replace "\\bam\\b" string "was")
(when matchp
(write-line "I was able to find and replace 'am' with 'was'."))))

View file

@ -0,0 +1,2 @@
[1]> (regexp:match "fox" "quick fox jumps")
#S(REGEXP:MATCH :START 6 :END 9)

View file

@ -0,0 +1,6 @@
[2]> (defun regexp-replace (pat repl string)
(reduce #'(lambda (x y) (string-concat x repl y))
(regexp:regexp-split pat string)))
REGEXP-REPLACE
[3]> (regexp-replace "x\\b" "-X-" "quick foxx jumps")
"quick fox-X- jumps"

View file

@ -0,0 +1,12 @@
void main() {
import std.stdio, std.regex;
immutable s = "I am a string";
// Test.
if (s.match("string$"))
"Ends with 'string'.".writeln;
// Substitute.
s.replace(" a ".regex, " another ").writeln;
}

View file

@ -0,0 +1,10 @@
RegExp regexp = new RegExp(r'\w+\!');
String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';
void main(){
String hello = 'hello hello! world world!';
String hellomodified = hello.replaceAllMapped(regexp, capitalize);
print(hello);
print(hellomodified);
}

View file

@ -0,0 +1,32 @@
program Regular_expressions;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.RegularExpressions;
const
CPP_IF = '\s*if\s*\(\s*(?<COND>.*)\s*\)\s*\{\s*return\s+(?<RETURN>.+);\s*\}';
PASCAL_IF = 'If ${COND} then result:= ${RETURN};';
var
RegularExpression: TRegEx;
str: string;
begin
str := ' if ( a < 0 ) { return -a; }';
Writeln('Expression: '#10#10, str);
if RegularExpression.Create(CPP_IF).IsMatch(str) then
begin
Writeln(#10' Is a single If in Cpp:'#10);
Writeln('Translate to Pascal:'#10);
str := RegularExpression.Create(CPP_IF).Replace(str, PASCAL_IF);
Writeln(str);
end;
readln;
end.

View file

@ -0,0 +1,2 @@
str = "This is a string"
if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"

View file

@ -0,0 +1,2 @@
str =~ ~r/this/ # => false
str =~ ~r/this/i # => true

View file

@ -0,0 +1,2 @@
str1 = ~r/a/ |> Regex.replace(str,"another")
str2 = str1 |> String.replace(~r/another/,"even another")

View file

@ -0,0 +1 @@
str3 = ~r/another/ |> Regex.replace(str2, fn x -> "#{String.upcase(x)}" end)

View file

@ -0,0 +1,4 @@
(let ((string "I am a string"))
(when (string-match-p "string$" string)
(message "Ends with 'string'"))
(message "%s" (replace-regexp-in-string " a " " another " string)))

View file

@ -0,0 +1,11 @@
match() ->
String = "This is a string",
case re:run(String, "string$") of
{match,_} -> io:format("Ends with 'string'~n");
_ -> ok
end.
substitute() ->
String = "This is a string",
NewString = re:replace(String, " a ", " another ", [{return, list}]),
io:format("~s~n",[NewString]).

View file

@ -0,0 +1,11 @@
open System
open System.Text.RegularExpressions
[<EntryPoint>]
let main argv =
let str = "I am a string"
if Regex("string$").IsMatch(str) then Console.WriteLine("Ends with string.")
let rstr = Regex(" a ").Replace(str, " another ")
Console.WriteLine(rstr)
0

View file

@ -0,0 +1,8 @@
USING: io kernel prettyprint regexp ;
IN: rosetta-code.regexp
"1000000" R/ 10+/ matches? . ! Does the entire string match the regexp?
"1001" R/ 10+/ matches? .
"1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere?
"blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print

View file

@ -0,0 +1,19 @@
include ffl/rgx.fs
\ Create a regular expression variable 'exp' in the dictionary
rgx-create exp
\ Compile an expression
s" Hello (World)" exp rgx-compile [IF]
.( Regular expression successful compiled.) cr
[THEN]
\ (Case sensitive) match a string with the expression
s" Hello World" exp rgx-cmatch? [IF]
.( String matches with the expression.) cr
[ELSE]
.( No match.) cr
[THEN]

View file

@ -0,0 +1,9 @@
Dim As String text = "I am a text"
If Right(text, 4) = "text" Then
Print "'" + text + "' ends with 'text'"
End If
Dim As Integer i = Instr(text, "am")
text = Left(text, i - 1) + "was" + Mid(text, i + 2)
Print "replace 'am' with 'was' = " + text
Sleep

View file

@ -0,0 +1,7 @@
line = "My name is Inigo Montoya."
for [first, last] = line =~ %r/my name is (\w+) (\w+)/ig
{
println["First name is: $first"]
println["Last name is: $last"]
}

View file

@ -0,0 +1 @@
line =~ %s/Frank/Frink/g

View file

@ -0,0 +1,11 @@
Public Sub Main()
Dim sString As String = "Hello world!"
If sString Ends "!" Then Print sString & " ends with !"
If sString Begins "Hel" Then Print sString & " begins with 'Hel'"
sString = Replace(sString, "world", "moon")
Print sString
End

View file

@ -0,0 +1,17 @@
[indent=4]
/* Regular expressions, in Genie */
init
var sentence = "This is a sample sentence."
try
var re = new Regex("s[ai]mple")
if re.match(sentence)
print "matched '%s' in '%s'", re.get_pattern(), sentence
var offs = 0
print("replace with 'different': %s",
re.replace(sentence, sentence.length, offs, "different"))
except err:RegexError
print err.message

View file

@ -0,0 +1,16 @@
package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
// Test
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
// Substitute
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}

View file

@ -0,0 +1,54 @@
import java.util.regex.*;
def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
def pepper = "Peter Piper picked a peck of pickled peppers"
println "=== Regular-expression String syntax (/string/) ==="
def woodRE = /[Ww]o\w+d/
def piperRE = /[Pp]\w+r/
assert woodRE instanceof String && piperRE instanceof String
assert (/[Ww]o\w+d/ == "[Ww]o\\w+d") && (/[Pp]\w+r/ == "[Pp]\\w+r")
println ([woodRE: woodRE, piperRE: piperRE])
println ()
println "=== Pattern (~) operator ==="
def woodPat = ~/[Ww]o\w+d/
def piperPat = ~piperRE
assert woodPat instanceof Pattern && piperPat instanceof Pattern
def woodList = woodchuck.split().grep(woodPat)
println ([exactTokenMatches: woodList])
println ([exactTokenMatches: pepper.split().grep(piperPat)])
println ()
println "=== Matcher (=~) operator ==="
def wwMatcher = (woodchuck =~ woodRE)
def ppMatcher = (pepper =~ /[Pp]\w+r/)
def wpMatcher = (woodchuck =~ /[Pp]\w+r/)
assert wwMatcher instanceof Matcher && ppMatcher instanceof Matcher
assert wwMatcher.toString() == woodPat.matcher(woodchuck).toString()
assert ppMatcher.toString() == piperPat.matcher(pepper).toString()
assert wpMatcher.toString() == piperPat.matcher(woodchuck).toString()
println ([ substringMatches: wwMatcher.collect { it }])
println ([ substringMatches: ppMatcher.collect { it }])
println ([ substringMatches: wpMatcher.collect { it }])
println ()
println "=== Exact Match (==~) operator ==="
def containsWoodRE = /.*/ + woodRE + /.*/
def containsPiperRE = /.*/ + piperRE + /.*/
def wwMatches = (woodchuck ==~ containsWoodRE)
assert wwMatches instanceof Boolean
def wwNotMatches = ! (woodchuck ==~ woodRE)
def ppMatches = (pepper ==~ containsPiperRE)
def pwNotMatches = ! (pepper ==~ containsWoodRE)
def wpNotMatches = ! (woodchuck ==~ containsPiperRE)
assert wwMatches && wwNotMatches && ppMatches && pwNotMatches && pwNotMatches
println ("'${woodchuck}' ${wwNotMatches ? 'does not' : 'does'} match '${woodRE}' exactly")
println ("'${woodchuck}' ${wwMatches ? 'does' : 'does not'} match '${containsWoodRE}' exactly")

View file

@ -0,0 +1 @@
println woodchuck.replaceAll(/c\w+k/, "CHUCK")

View file

@ -0,0 +1,11 @@
def ck = (woodchuck =~ /c\w+k/)
println (ck.replaceAll("CHUCK"))
println (ck.replaceAll("wind"))
println (ck.replaceAll("pile"))
println (ck.replaceAll("craft"))
println (ck.replaceAll("block"))
println (ck.replaceAll("row"))
println (ck.replaceAll("shed"))
println (ck.replaceAll("man"))
println (ck.replaceAll("work"))
println (ck.replaceAll("pickle"))

View file

@ -0,0 +1,7 @@
import Text.Regex
str = "I am a string"
case matchRegex (mkRegex ".*string$") str of
Just _ -> putStrLn $ "ends with 'string'"
Nothing -> return ()

View file

@ -0,0 +1,5 @@
import Text.Regex
orig = "I am the original string"
result = subRegex (mkRegex "original") orig "modified"
putStrLn $ result

View file

@ -0,0 +1,7 @@
CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" /
REAL, PARAMETER :: Regex=128, Count=256
characters_a_m = INDEX(string, "[a-m]", Regex+Count) ! counts 16
vocals_changed = EDIT(Text=string, Option=Regex, Right="[aeiou]", RePLaceby='**', DO=LEN(string) ) ! changes 11
WRITE(ClipBoard) string ! Th** q****ck br**wn f**x j**mps **v**r th** l**zy d**g

View file

@ -0,0 +1,12 @@
procedure main()
s := "A simple string"
p := "string$" # regular expression
s ? write(image(s),if ReFind(p) then " matches " else " doesn't match ",image(p))
s[j := ReFind(p,s):ReMatch(p,s,j)] := "replacement"
write(image(s))
end
link regexp # link to IPL regexp

View file

@ -0,0 +1,4 @@
let T be indexed text;
let T be "A simple string";
if T matches the regular expression ".*string$", say "ends with string.";
replace the regular expression "simple" in T with "replacement";

View file

@ -0,0 +1,2 @@
load'regex' NB. Load regex library
str =: 'I am a string' NB. String used in examples.

View file

@ -0,0 +1,2 @@
'.*string$' rxeq str NB. 1 is true, 0 is false
1

View file

@ -0,0 +1,2 @@
('am';'am still') rxrplc str
I am still a string

View file

@ -0,0 +1 @@
open'regex'

View file

@ -0,0 +1,5 @@
/* match entire string against a pattern */
boolean isNumber = "-1234.567".matches("-?\\d+(?:\\.\\d+)?");
/* substitute part of string using a pattern */
String reduceSpaces = "a b c d e f".replaceAll(" +", " ");

View file

@ -0,0 +1,12 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
/* group capturing example */
Pattern pattern = Pattern.compile("(?:(https?)://)?([^/]+)/(?:([^#]+)(?:#(.+))?)?");
Matcher matcher = pattern.matcher("https://rosettacode.org/wiki/Regular_expressions#Java");
if (matcher.find()) {
String protocol = matcher.group(1);
String authority = matcher.group(2);
String path = matcher.group(3);
String fragment = matcher.group(4);
}

View file

@ -0,0 +1,2 @@
/* split a string using a pattern */
String[] strings = "abc\r\ndef\r\nghi".split("\r\n?");

View file

@ -0,0 +1,4 @@
String str = "I am a string";
if (str.matches(".*string")) { // note: matches() tests if the entire string is a match
System.out.println("ends with 'string'");
}

View file

@ -0,0 +1,6 @@
import java.util.regex.*;
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher(str);
while (m.find()) {
// use m.group() to extract matches
}

View file

@ -0,0 +1,3 @@
String orig = "I am the original string";
String result = orig.replaceAll("original", "modified");
// result is now "I am the modified string"

View file

@ -0,0 +1,15 @@
var subject = "Hello world!";
// Two different ways to create the RegExp object
// Both examples use the exact same pattern... matching "hello "
var re_PatternToMatch = /Hello (World)/i; // creates a RegExp literal with case-insensitivity
var re_PatternToMatch2 = new RegExp("Hello (World)", "i");
// Test for a match - return a bool
var isMatch = re_PatternToMatch.test(subject);
// Get the match details
// Returns an array with the match's details
// matches[0] == "Hello world"
// matches[1] == "world"
var matches = re_PatternToMatch2.exec(subject);

View file

@ -0,0 +1,5 @@
var subject = "Hello world!";
// Perform a string replacement
// newSubject == "Replaced!"
var newSubject = subject.replace(re_PatternToMatch, "Replaced");

View file

@ -0,0 +1 @@
"I am a string" | test("string$")

View file

@ -0,0 +1 @@
"I am a string" | sub(" a "; " another ")

View file

@ -0,0 +1 @@
"abc" | sub( "(?<head>^.)(?<tail>.*)"; "\(.head)-\(.tail)")

View file

@ -0,0 +1,10 @@
/* Regular expressions, in Jsish */
var re = /s[ai]mple/;
var sentence = 'This is a sample sentence';
var matches = sentence.match(re);
if (matches.length > 0) printf('%s found in "%s" using %q\n', matches[0], sentence, re);
var replaced = sentence.replace(re, "different");
printf("replaced sentence is: %s\n", replaced);

View file

@ -0,0 +1,4 @@
s = "I am a string"
if ismatch(r"string$", s)
println("'$s' ends with 'string'")
end

View file

@ -0,0 +1,2 @@
s = "I am a string"
s = replace(s, r" (a|an) ", " another ")

View file

@ -0,0 +1,11 @@
// version 1.0.6
fun main(args: Array<String>) {
val s1 = "I am the original string"
val r1 = Regex("^.*string$")
if (s1.matches(r1)) println("`$s1` matches `$r1`")
val r2 = Regex("original")
val s3 = "replacement"
val s2 = s1.replace(r2, s3)
if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
}

View file

@ -0,0 +1 @@
if matching(re/abc/, "somestring") { ... }

View file

@ -0,0 +1 @@
if val .x, .y = submatch(re/(abc+).+?(def)/, "somestring") { ... }

View file

@ -0,0 +1 @@
if val (.x, .y) = submatch(re/(abc+).+?(def)/, "somestring") { ... }

View file

@ -0,0 +1,4 @@
given "somestring" {
case re/abc/: ...
...
}

View file

@ -0,0 +1,4 @@
given re/abc/ {
case "somestring": ...
...
}

View file

@ -0,0 +1,2 @@
replace("abcdef", re/abc/, "Y")
# result: "Ydef"

View file

@ -0,0 +1,22 @@
local(mytext = 'My name is: Stone, Rosetta
My name is: Hippo, Campus
')
local(regexp = regexp(
-find = `(?m)^My name is: (.*?), (.*?)$`,
-input = #mytext,
-replace = `Hello! I am $2 $1`,
-ignorecase
))
while(#regexp -> find) => {^
#regexp -> groupcount > 1 ? (#regexp -> matchString(2) -> trim&) + '<br />'
^}
#regexp -> reset(-input = #mytext)
#regexp -> findall
#regexp -> reset(-input = #mytext)
'<br />'
#regexp -> replaceall

View file

@ -0,0 +1,9 @@
test = "My name is Lua."
pattern = ".*name is (%a*).*"
if test:match(pattern) then
print("Name found.")
end
sub, num_matches = test:gsub(pattern, "Hello, %1!")
print(sub)

View file

@ -0,0 +1,73 @@
Module CheckIt {
declare global ObjRegEx "VBscript.RegExp"
Function RegEx.Replace$(from$, what$) {
Method ObjRegEx, "Replace", from$, what$ as response$
=response$
}
Function RegEx.Test(what$) {
Method ObjRegEx, "Test", what$ as response
=response
}
Print Type$(ObjRegEx)
With ObjRegEx, "Global", True, "Pattern" as pattern$
pattern$="Mona Lisa"
Print RegEx.Test("The Mona Lisa is in the Louvre.")=true
Print RegEx.Replace$("The Mona Lisa is in the Louvre.", "La Gioconda")
Pattern$ = " {2,}"
Print "Myer Ken, Vice President, Sales and Services"
\\ Removing some spaces
Print RegEx.Replace$("Myer Ken, Vice President, Sales and Services", " ")
pattern$="(\d{3})-(\d{3})-(\d{4})"
Method ObjRegEx, "Execute", "555-123-4567, 555-943-6717" as MyMatches
Print Type$(MyMatches) ' it is a IMatchCollection2
With MyMatches, "Count" as count, "Item" as List$()
For i=0 to Count-1 : Print List$(i) : Next i
Print RegEx.Replace$("555-123-4567, 555-943-6717", "($1) $2-$3")
Pattern$ = "(\S+), (\S+)"
Print RegEx.Replace$("Myer, Ken", "$2 $1")
Method ObjRegEx, "Execute", "Myer, Ken" as MyMatches
Rem : DisplayFunctions(MyMatches)
\\ we can use Enumerator
With MyMatches, "_NewEnum" as New Matches
Rem : DisplayFunctions(Matches)
With Matches, "Value" as New item$
While Matches {
Print Item$
}
\\ Or just using the list$()
For i=0 to Count-1 : Print List$(i) : Next i
declare ObjRegEx Nothing
End
Sub DisplayFunctions(x)
Local cc=param(x), ec=each(cc)
while ec {
Print eval$(ec) ' print every function/property of object x
}
End Sub
}
Checkit
\\ internal has no pattern. There is a like operator (~) for strings which use pattern matching (using VB6 like). We can use Instr() and RInstr() for strings.
Module Internal {
what$="Mona Lisa"
Document a$="The Mona Lisa is in the Louvre."
Find a$, what$
Read FindWhere
If FindWhere<>0 then Read parNo, parlocation
\\ replace in place
Insert FindWhere, Len(what$) a$="La Gioconda"
Report a$
n$="The Mona Lisa is in the Louvre, not the Mona Lisa"
Report Replace$("Mona Lisa", "La Gioconda", n$, 1, 1) ' replace from start only one
dim a$()
a$()=Piece$("Myer, Ken",", ")
Print a$(1)+", "+a$(0)="Ken, Myer"
}
Internal

View file

@ -0,0 +1,2 @@
regexp(`GNUs not Unix', `\<[a-z]\w+')
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')

View file

@ -0,0 +1,39 @@
samples = #("Some string 123","Example text 123","string",\
"ThisString Will Not Match","A123,333,string","123451")
samples2 = #("I am a string","Me too.")
regex = dotnetobject "System.Text.RegularExpressions.Regex" ".*\bstring*"
regex2 = dotnetobject "System.Text.RegularExpressions.Regex" "\ba\b"
clearlistener()
format "Pattern is : %\n" (regex.toString())
for i in samples do
(
if regex.ismatch(i) then
(
format "The string \"%\" matches the pattern\n" i
)
else
(
format "The string \"%\" doesn't match the pattern\n" i
)
)
-- replacement
format "Pattern is : %\n" (regex2.toString())
for i in samples2 do
(
if regex2.ismatch(i) then
(
local replaced = regex2.replace i "another"
format "The string \"%\" matched the pattern, so it was replaced: \"%\"\n" i replaced
)
else
(
format "The string \"%\" does not match the pattern\n" i
)
)

View file

@ -0,0 +1,13 @@
alias regular_expressions {
var %string = This is a string
var %re = string$
if ($regex(%string,%re) > 0) {
echo -a Ends with string.
}
%re = \ba\b
if ($regsub(%string,%re,another,%string) > 0) {
echo -a Result 1: %string
}
%re = \b(another)\b
echo -a Result 2: $regsubex(%string,%re,yet \1)
}

View file

@ -0,0 +1,13 @@
REGEXP
NEW HI,W,PATTERN,BOOLEAN
SET HI="Hello, world!",W="world"
SET PATTERN=".E1"""_W_""".E"
SET BOOLEAN=HI?@PATTERN
WRITE "Source string - '"_HI_"'",!
WRITE "Partial string - '"_W_"'",!
WRITE "Pattern string created is - '"_PATTERN_"'",!
WRITE "Match? ",$SELECT(BOOLEAN:"YES",'BOOLEAN:"No"),!
;
SET BOOLEAN=$FIND(HI,W)
IF BOOLEAN>0 WRITE $PIECE(HI,W,1)_"string"_$PIECE(HI,W,2)
QUIT

View file

@ -0,0 +1,5 @@
#Examples from Maple Help
StringTools:-RegMatch("^ab+bc$", "abbbbc");
StringTools:-RegMatch("^ab+bc$", "abbbbcx");
StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2");
StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");

View file

@ -0,0 +1,2 @@
StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]]
StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]

View file

@ -0,0 +1,37 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.regex.
st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman'
rx1 = 'f.e.*?'
sbx = 'foo'
rx1ef = '(?i)'rx1 -- use embedded flag expression == Pattern.CASE_INSENSITIVE
-- using String's matches & replaceAll
mcm = (String st1).matches(rx1ef)
say 'String "'st1'"' 'matches pattern "'rx1ef'":' Boolean(mcm)
say
say 'Replace all occurrences of regex pattern "'rx1ef'" with "'sbx'"'
stx = Rexx
stx = (String st1).replaceAll(rx1ef, sbx)
say 'Input string: "'st1'"'
say 'Result string: "'stx'"'
say
-- using java.util.regex classes
pt1 = Pattern.compile(rx1, Pattern.CASE_INSENSITIVE)
mc1 = pt1.matcher(st1)
mcm = mc1.matches()
say 'String "'st1'"' 'matches pattern "'pt1.toString()'":' Boolean(mcm)
mc1 = pt1.matcher(st1)
say
say 'Replace all occurrences of regex pattern "'rx1'" with "'sbx'"'
sx1 = Rexx
sx1 = mc1.replaceAll(sbx)
say 'Input string: "'st1'"'
say 'Result string: "'sx1'"'
say
return

View file

@ -0,0 +1 @@
(regex "[bB]+" "AbBBbABbBAAAA") -> ("bBBb" 1 4)

View file

@ -0,0 +1,9 @@
import re
var s = "This is a string"
if s.find(re"string$") > -1:
echo "Ends with string."
s = s.replace(re"\ a\ ", " another ")
echo s

View file

@ -0,0 +1,7 @@
#load "str.cma";;
let str = "I am a string";;
try
ignore(Str.search_forward (Str.regexp ".*string$") str 0);
print_endline "ends with 'string'"
with Not_found -> ()
;;

View file

@ -0,0 +1,4 @@
#load "str.cma";;
let orig = "I am the original string";;
let result = Str.global_replace (Str.regexp "original") "modified" orig;;
(* result is now "I am the modified string" *)

Some files were not shown because too many files have changed in this diff Show more