Regular expressions: Difference between revisions

Content added Content deleted
(→‎{{header|Wren}}: Added a second version using Wren-regex module.)
m (syntax highlighting fixup automation)
Line 15: Line 15:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V string = ‘This is a string’
<syntaxhighlight lang="11l">V string = ‘This is a string’


I re:‘string$’.search(string)
I re:‘string$’.search(string)
Line 21: Line 21:


string = string.replace(re:‘ a ’, ‘ another ’)
string = string.replace(re:‘ a ’, ‘ another ’)
print(string)</lang>
print(string)</syntaxhighlight>


{{out}}
{{out}}
Line 30: Line 30:


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
"haystack" /a./ r:match . cr
"haystack" /a./ r:match . cr
"haystack" /a./ "blah" s:replace! . cr
"haystack" /a./ "blah" s:replace! . cr
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 42: Line 42:
=={{header|ABAP}}==
=={{header|ABAP}}==


<syntaxhighlight lang="abap">
<lang ABAP>
DATA: text TYPE string VALUE 'This is a Test'.
DATA: text TYPE string VALUE 'This is a Test'.


Line 54: Line 54:
cl_demo_output=>write( text ).
cl_demo_output=>write( text ).
cl_demo_output=>display( ).
cl_demo_output=>display( ).
</syntaxhighlight>
</lang>


Output:
Output:
Line 66: Line 66:
There is no Regular Expression library in the Ada Standard,
There is no Regular Expression library in the Ada Standard,
so I am using one of the libraries provided by gnat/gcc.
so I am using one of the libraries provided by gnat/gcc.
<lang ada>with Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;


procedure Regex is
procedure Regex is
Line 108: Line 108:
Str := Str(Str'First .. First-1) & "pattern" & Str(Last+1 .. Str'Last);
Str := Str(Str'First .. First-1) & "pattern" & Str(Last+1 .. Str'Last);
Put_Line(Str);
Put_Line(Str);
end Regex;</lang>
end Regex;</syntaxhighlight>


{{out}}
{{out}}
Line 123: Line 123:
<!-- {{does not work with|ALGOL 68|Standard - grep/sub in string are not part of the standard's prelude. }} -->
<!-- {{does not work with|ALGOL 68|Standard - grep/sub in string are not part of the standard's prelude. }} -->
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<lang algol68>INT match=0, no match=1, out of memory error=2, other error=3;
<syntaxhighlight lang="algol68">INT match=0, no match=1, out of memory error=2, other error=3;


STRING str := "i am a string";
STRING str := "i am a string";
Line 135: Line 135:
# Replace: #
# Replace: #


IF sub in string(" a ", " another ",str) = match THEN printf(($gl$, str)) FI;</lang>
IF sub in string(" a ", " another ",str) = match THEN printf(($gl$, str)) FI;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 151: Line 151:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}


For example:<lang algol68>FORMAT pattern = $ddd" "c("cats","dogs")$;
For example:<syntaxhighlight lang="algol68">FORMAT pattern = $ddd" "c("cats","dogs")$;
FILE file; STRING book; associate(file, book);
FILE file; STRING book; associate(file, book);
on value error(file, (REF FILE f)BOOL: stop);
on value error(file, (REF FILE f)BOOL: stop);
Line 162: Line 162:
print(("Dalmatians: ", dalmatians, new line));
print(("Dalmatians: ", dalmatians, new line));
count OF dalmatians +:=1;
count OF dalmatians +:=1;
printf(($"Gives: "$, pattern, dalmatians, $l$))</lang>
printf(($"Gives: "$, pattern, dalmatians, $l$))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 171: Line 171:
=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
task 1: match a string against a regular expression (Hopper use POSIX):
task 1: match a string against a regular expression (Hopper use POSIX):
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>


Line 186: Line 186:
exit(0)
exit(0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 192: Line 192:
</pre>
</pre>
Task 2: Hopper does not substitute using regular expressions, but using proper functions.
Task 2: Hopper does not substitute using regular expressions, but using proper functions.
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>


Line 221: Line 221:


exit(0)
exit(0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 230: Line 230:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{libheader|Satimage.osax}}
{{libheader|Satimage.osax}}
<lang applescript>try
<syntaxhighlight lang="applescript">try
find text ".*string$" in "I am a string" with regexp
find text ".*string$" in "I am a string" with regexp
on error message
on error message
Line 240: Line 240:
on error message
on error message
return message
return message
end try</lang>
end try</syntaxhighlight>
----
----
As from macOS 10.14 Mojave, third-party scripting additions (OSAXen) such as the Satimage OSAX are essentially unusable. (One of Apple's increasingly tight security measures.) They ''are'' allowed under very strict conditions as part of an application's own resources and [https://latenightsw.com Late Night Software], the developer of Script Debugger, has released a [https://forum.latenightsw.com/t/use-satimage-scripting-additions-on-catalina-and-mojave/1576 SatimageOSAX] application as a stop-gap measure to allow existing Satimage-dependent scripts to be used with minimal editing until they're rewritten to use other commands.
As from macOS 10.14 Mojave, third-party scripting additions (OSAXen) such as the Satimage OSAX are essentially unusable. (One of Apple's increasingly tight security measures.) They ''are'' allowed under very strict conditions as part of an application's own resources and [https://latenightsw.com Late Night Software], the developer of Script Debugger, has released a [https://forum.latenightsw.com/t/use-satimage-scripting-additions-on-catalina-and-mojave/1576 SatimageOSAX] application as a stop-gap measure to allow existing Satimage-dependent scripts to be used with minimal editing until they're rewritten to use other commands.
Line 247: Line 247:


'''do shell script:'''
'''do shell script:'''
<lang applescript>-- Get the run of non-white-space at the end, if any.
<syntaxhighlight lang="applescript">-- Get the run of non-white-space at the end, if any.
try
try
set output to (do shell script "echo 'I am a string' | egrep -o '\\S+$'")
set output to (do shell script "echo 'I am a string' | egrep -o '\\S+$'")
Line 255: Line 255:
-- Replace the first instance of "orig…" with "modified".
-- 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/'")
set moreOutput to(do shell script "echo 'I am the original string' | sed 's/orig[a-z]*/modified/'")
return output & linefeed & moreOutput</lang>
return output & linefeed & moreOutput</syntaxhighlight>


'''ASObjC''' uses [http://userguide.icu-project.org/strings/regexp ICU regex]:
'''ASObjC''' uses [http://userguide.icu-project.org/strings/regexp ICU regex]:
<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 281: Line 281:
end if
end if


return (output as text) & linefeed & moreOutput</lang>
return (output as text) & linefeed & moreOutput</syntaxhighlight>
As an alternative to the NSString regex options used above, there's also a dedicated NSRegularExpression class:
As an alternative to the NSString regex options used above, there's also a dedicated NSRegularExpression class:
<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 306: Line 306:
end if
end if


return (output as text) & linefeed & moreOutput</lang>
return (output as text) & linefeed & moreOutput</syntaxhighlight>


{{out}}
{{out}}
Line 316: Line 316:


=={{header|Argile}}==
=={{header|Argile}}==
<lang Argile>use std, regex
<syntaxhighlight lang="argile">use std, regex


(: matching :)
(: matching :)
Line 337: Line 337:
uninit regex
uninit regex


check mem leak; use dbg (:optional:)</lang>
check mem leak; use dbg (:optional:)</syntaxhighlight>


(note that it needs to be compiled with argrt library)
(note that it needs to be compiled with argrt library)
Line 348: Line 348:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>s: "This is a string"
<syntaxhighlight lang="rebol">s: "This is a string"
if contains? s {/string$/} -> print "yes, it ends with 'string'"
if contains? s {/string$/} -> print "yes, it ends with 'string'"
Line 354: Line 354:
replace 's {/[as]/} "x"
replace 's {/[as]/} "x"


print s</lang>
print s</syntaxhighlight>


{{out}}
{{out}}
Line 362: Line 362:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % foundpos := RegExMatch("Hello World", "World$")
<syntaxhighlight lang="autohotkey">MsgBox % foundpos := RegExMatch("Hello World", "World$")
MsgBox % replaced := RegExReplace("Hello World", "World$", "yourself")</lang>
MsgBox % replaced := RegExReplace("Hello World", "World$", "yourself")</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
AWK supports regular expressions, which are typically enclosed using slash symbols at the front and back, and the tilde regular expression binding operator:
AWK supports regular expressions, which are typically enclosed using slash symbols at the front and back, and the tilde regular expression binding operator:
<lang awk>$ awk '{if($0~/[A-Z]/)print "uppercase detected"}'
<syntaxhighlight lang="awk">$ awk '{if($0~/[A-Z]/)print "uppercase detected"}'
abc
abc
ABC
ABC
uppercase detected</lang>
uppercase detected</syntaxhighlight>
As shorthand, a regular expression in the condition part fires if it matches an input line:
As shorthand, a regular expression in the condition part fires if it matches an input line:
<lang awk>awk '/[A-Z]/{print "uppercase detected"}'
<syntaxhighlight lang="awk">awk '/[A-Z]/{print "uppercase detected"}'
def
def
DeF
DeF
uppercase detected</lang>
uppercase detected</syntaxhighlight>
For substitution, the first argument can be a regular expression, while the replacement string is constant (only that '&' in it receives the value of the match):
For substitution, the first argument can be a regular expression, while the replacement string is constant (only that '&' in it receives the value of the match):
<lang awk>$ awk '{gsub(/[A-Z]/,"*");print}'
<syntaxhighlight lang="awk">$ awk '{gsub(/[A-Z]/,"*");print}'
abCDefG
abCDefG
ab**ef*
ab**ef*
$ awk '{gsub(/[A-Z]/,"(&)");print}'
$ awk '{gsub(/[A-Z]/,"(&)");print}'
abCDefGH
abCDefGH
ab(C)(D)ef(G)(H)</lang>
ab(C)(D)ef(G)(H)</syntaxhighlight>
This variant matches one or more uppercase letters in one round:
This variant matches one or more uppercase letters in one round:
<lang awk>$ awk '{gsub(/[A-Z]+/,"(&)");print}'
<syntaxhighlight lang="awk">$ awk '{gsub(/[A-Z]+/,"(&)");print}'
abCDefGH
abCDefGH
ab(CD)ef(GH)</lang>
ab(CD)ef(GH)</syntaxhighlight>


Regular expression negation can be achieved by combining the regular expression binding operator with a logical not operator, as follows:
Regular expression negation can be achieved by combining the regular expression binding operator with a logical not operator, as follows:
Line 397: Line 397:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Uses the [http://people.delphiforums.com/gjc/gnu_regex.html gnu_regex] library.
Uses the [http://people.delphiforums.com/gjc/gnu_regex.html gnu_regex] library.
<lang bbcbasic> SYS "LoadLibrary", "gnu_regex.dll" TO gnu_regex%
<syntaxhighlight lang="bbcbasic"> SYS "LoadLibrary", "gnu_regex.dll" TO gnu_regex%
IF gnu_regex% = 0 ERROR 100, "Cannot load gnu_regex.dll"
IF gnu_regex% = 0 ERROR 100, "Cannot load gnu_regex.dll"
SYS "GetProcAddress", gnu_regex%, "regcomp" TO regcomp
SYS "GetProcAddress", gnu_regex%, "regcomp" TO regcomp
Line 436: Line 436:
ENDIF
ENDIF


SYS "FreeLibrary", gnu_regex%</lang>
SYS "FreeLibrary", gnu_regex%</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 455: Line 455:


List all rational numbers smaller then 7 hidden in the string "fgsakg789/35768685432fkgha"
List all rational numbers smaller then 7 hidden in the string "fgsakg789/35768685432fkgha"
<lang bracmat>@("fesylk789/35768poq2art":? (#<7:?n & out$!n & ~) ?)</lang>
<syntaxhighlight lang="bracmat">@("fesylk789/35768poq2art":? (#<7:?n & out$!n & ~) ?)</syntaxhighlight>
{{out}}
{{out}}
<pre>789/357
<pre>789/357
Line 480: Line 480:
Test
Test


<lang brat>str = "I am a string"
<syntaxhighlight lang="brat">str = "I am a string"


true? str.match(/string$/)
true? str.match(/string$/)
Line 487: Line 487:
false? str.match(/^You/)
false? str.match(/^You/)
{ p "Does not start with 'You'" }
{ p "Does not start with 'You'" }
</syntaxhighlight>
</lang>


Substitute
Substitute


<lang brat># Substitute in copy
<syntaxhighlight lang="brat"># Substitute in copy


str2 = str.sub(/ a /, " another ")
str2 = str.sub(/ a /, " another ")
Line 510: Line 510:


p str # prints "I Am Another string"
p str # prints "I Am Another string"
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 517: Line 517:
As far as I can see, POSIX defined function for regex matching, but nothing for substitution. So we must do all the hard work ''by hand''. The complex-appearing code could be turned into a function.
As far as I can see, POSIX defined function for regex matching, but nothing for substitution. So we must do all the hard work ''by hand''. The complex-appearing code could be turned into a function.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/types.h>
Line 559: Line 559:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===Alternative using GLib===
===Alternative using GLib===
The task is a bit easier with GLib's Perl-compatible regular expression functionality.
The task is a bit easier with GLib's Perl-compatible regular expression functionality.
{{libheader|GLib}}
{{libheader|GLib}}
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <glib.h>
#include <glib.h>


Line 617: Line 617:
regex_replace_demo();
regex_replace_demo();
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 628: Line 628:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;


Line 642: Line 642:
Console.WriteLine(str);
Console.WriteLine(str);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 648: Line 648:
Standards earlier than C++11 can make use of Boost's Regex library via boost/regex.hpp
Standards earlier than C++11 can make use of Boost's Regex library via boost/regex.hpp


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>
#include <iterator>
#include <iterator>
Line 686: Line 686:
"'m now a changed");
"'m now a changed");
std::cout << dest_string << std::endl;
std::cout << dest_string << std::endl;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(let [s "I am a string"]
<syntaxhighlight lang="clojure">(let [s "I am a string"]
;; match
;; match
(when (re-find #"string$" s)
(when (re-find #"string$" s)
Line 698: Line 698:
;; substitute
;; substitute
(println (clojure.string/replace s " a " " another "))
(println (clojure.string/replace s " a " " another "))
)</lang>
)</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 705: Line 705:
Uses [http://weitz.de/cl-ppcre/ CL-PPCRE - Portable Perl-compatible regular expressions for Common Lisp].
Uses [http://weitz.de/cl-ppcre/ CL-PPCRE - Portable Perl-compatible regular expressions for Common Lisp].


<lang lisp>(let ((string "I am a string"))
<syntaxhighlight lang="lisp">(let ((string "I am a string"))
(when (cl-ppcre:scan "string$" string)
(when (cl-ppcre:scan "string$" string)
(write-line "Ends with string"))
(write-line "Ends with string"))
(unless (cl-ppcre:scan "^You" string )
(unless (cl-ppcre:scan "^You" string )
(write-line "Does not start with 'You'")))</lang>
(write-line "Does not start with 'You'")))</syntaxhighlight>


Substitute
Substitute


<lang lisp>(let* ((string "I am a string")
<syntaxhighlight lang="lisp">(let* ((string "I am a string")
(string (cl-ppcre:regex-replace " a " string " another ")))
(string (cl-ppcre:regex-replace " a " string " another ")))
(write-line string))</lang>
(write-line string))</syntaxhighlight>


Test and Substitute
Test and Substitute


<lang lisp>(let ((string "I am a string"))
<syntaxhighlight lang="lisp">(let ((string "I am a string"))
(multiple-value-bind (string matchp)
(multiple-value-bind (string matchp)
(cl-ppcre:regex-replace "\\bam\\b" string "was")
(cl-ppcre:regex-replace "\\bam\\b" string "was")
(when matchp
(when matchp
(write-line "I was able to find and replace 'am' with 'was'."))))</lang>
(write-line "I was able to find and replace 'am' with 'was'."))))</syntaxhighlight>


===CLISP regexp engine===
===CLISP regexp engine===
{{works with|CLISP}}
{{works with|CLISP}}
[[Clisp]] comes with [http://clisp.org/impnotes/regexp-mod.html built-in regexp matcher]. On a Clisp prompt:
[[Clisp]] comes with [http://clisp.org/impnotes/regexp-mod.html built-in regexp matcher]. On a Clisp prompt:
<lang lisp>[1]> (regexp:match "fox" "quick fox jumps")
<syntaxhighlight lang="lisp">[1]> (regexp:match "fox" "quick fox jumps")
#S(REGEXP:MATCH :START 6 :END 9)</lang>
#S(REGEXP:MATCH :START 6 :END 9)</syntaxhighlight>
To find all matches, loop with different <code>:start</code> keyword.
To find all matches, loop with different <code>:start</code> keyword.


Replacing text can be done with the help of <code>REGEXP:REGEXP-SPLIT</code> function:
Replacing text can be done with the help of <code>REGEXP:REGEXP-SPLIT</code> function:
<lang lisp>[2]> (defun regexp-replace (pat repl string)
<syntaxhighlight lang="lisp">[2]> (defun regexp-replace (pat repl string)
(reduce #'(lambda (x y) (string-concat x repl y))
(reduce #'(lambda (x y) (string-concat x repl y))
(regexp:regexp-split pat string)))
(regexp:regexp-split pat string)))
REGEXP-REPLACE
REGEXP-REPLACE
[3]> (regexp-replace "x\\b" "-X-" "quick foxx jumps")
[3]> (regexp-replace "x\\b" "-X-" "quick foxx jumps")
"quick fox-X- jumps"</lang>
"quick fox-X- jumps"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.regex;
import std.stdio, std.regex;


Line 752: Line 752:
// Substitute.
// Substitute.
s.replace(" a ".regex, " another ").writeln;
s.replace(" a ".regex, " another ").writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Ends with 'string'.
<pre>Ends with 'string'.
Line 759: Line 759:


=={{header|Dart}}==
=={{header|Dart}}==
<lang d>RegExp regexp = new RegExp(r'\w+\!');
<syntaxhighlight lang="d">RegExp regexp = new RegExp(r'\w+\!');


String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';
String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';
Line 768: Line 768:
print(hello);
print(hello);
print(hellomodified);
print(hellomodified);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>hello hello! world world!
<pre>hello hello! world world!
Line 776: Line 776:
{{libheader| System.RegularExpressions}}
{{libheader| System.RegularExpressions}}
Sample program that uses a regex, for translate a line of code in cpp to pascal.
Sample program that uses a regex, for translate a line of code in cpp to pascal.
<syntaxhighlight lang="delphi">
<lang Delphi>
program Regular_expressions;
program Regular_expressions;


Line 810: Line 810:
end.
end.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 826: Line 826:
=={{header|Elixir}}==
=={{header|Elixir}}==
Elixir allows pattern matching using the <code>~r</code> sigil.
Elixir allows pattern matching using the <code>~r</code> sigil.
<syntaxhighlight lang="elixir">
<lang Elixir>
str = "This is a string"
str = "This is a string"
if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"
if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"
</syntaxhighlight>
</lang>
A number of modifiers can be appended to the regular expression; <code>~r/pattern/i</code>, for instance, toggles case insensitivity.
A number of modifiers can be appended to the regular expression; <code>~r/pattern/i</code>, for instance, toggles case insensitivity.
<syntaxhighlight lang="elixir">
<lang Elixir>
str =~ ~r/this/ # => false
str =~ ~r/this/ # => false
str =~ ~r/this/i # => true
str =~ ~r/this/i # => true
</syntaxhighlight>
</lang>
Both <code>Regex</code> and <code>String</code> have a <code>replace</code> function.
Both <code>Regex</code> and <code>String</code> have a <code>replace</code> function.
<syntaxhighlight lang="elixir">
<lang Elixir>
str1 = ~r/a/ |> Regex.replace(str,"another")
str1 = ~r/a/ |> Regex.replace(str,"another")
str2 = str1 |> String.replace(~r/another/,"even another")
str2 = str1 |> String.replace(~r/another/,"even another")
</syntaxhighlight>
</lang>
<code>Regex.replace</code> allows for a function to be used as a replacement value. A function can modify the found pattern.
<code>Regex.replace</code> allows for a function to be used as a replacement value. A function can modify the found pattern.
<syntaxhighlight lang="elixir">
<lang Elixir>
str3 = ~r/another/ |> Regex.replace(str2, fn x -> "#{String.upcase(x)}" end)
str3 = ~r/another/ |> Regex.replace(str2, fn x -> "#{String.upcase(x)}" end)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 854: Line 854:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(let ((string "I am a string"))
<syntaxhighlight lang="lisp">(let ((string "I am a string"))
(when (string-match-p "string$" string)
(when (string-match-p "string$" string)
(message "Ends with 'string'"))
(message "Ends with 'string'"))
(message "%s" (replace-regexp-in-string " a " " another " string)))</lang>
(message "%s" (replace-regexp-in-string " a " " another " string)))</syntaxhighlight>


{{out}}
{{out}}
Line 865: Line 865:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>match() ->
<syntaxhighlight lang="erlang">match() ->
String = "This is a string",
String = "This is a string",
case re:run(String, "string$") of
case re:run(String, "string$") of
Line 875: Line 875:
String = "This is a string",
String = "This is a string",
NewString = re:replace(String, " a ", " another ", [{return, list}]),
NewString = re:replace(String, " a ", " another ", [{return, list}]),
io:format("~s~n",[NewString]).</lang>
io:format("~s~n",[NewString]).</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.Text.RegularExpressions
open System.Text.RegularExpressions


Line 889: Line 889:
let rstr = Regex(" a ").Replace(str, " another ")
let rstr = Regex(" a ").Replace(str, " another ")
Console.WriteLine(rstr)
Console.WriteLine(rstr)
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io kernel prettyprint regexp ;
<syntaxhighlight lang="factor">USING: io kernel prettyprint regexp ;
IN: rosetta-code.regexp
IN: rosetta-code.regexp


Line 899: Line 899:
"1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere?
"1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere?


"blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print</lang>
"blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 911: Line 911:
{{libheader|Forth Foundation Library}}
{{libheader|Forth Foundation Library}}
Test/Match
Test/Match
<lang forth>include ffl/rgx.fs
<syntaxhighlight lang="forth">include ffl/rgx.fs


\ Create a regular expression variable 'exp' in the dictionary
\ Create a regular expression variable 'exp' in the dictionary
Line 929: Line 929:
[ELSE]
[ELSE]
.( No match.) cr
.( No match.) cr
[THEN]</lang>
[THEN]</syntaxhighlight>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As String text = "I am a text"
Dim As String text = "I am a text"
If Right(text, 4) = "text" Then
If Right(text, 4) = "text" Then
Line 943: Line 943:
Print "replace 'am' with 'was' = " + text
Print "replace 'am' with 'was' = " + text
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>'I am a text' ends with 'text'
<pre>'I am a text' ends with 'text'
Line 951: Line 951:
=={{header|Frink}}==
=={{header|Frink}}==
Pattern matching:
Pattern matching:
<lang frink>
<syntaxhighlight lang="frink">
line = "My name is Inigo Montoya."
line = "My name is Inigo Montoya."


Line 959: Line 959:
println["Last name is: $last"]
println["Last name is: $last"]
}
}
</syntaxhighlight>
</lang>


Replacement: (Replaces in the variable <code>line</code>)
Replacement: (Replaces in the variable <code>line</code>)
<lang frink>
<syntaxhighlight lang="frink">
line =~ %s/Frank/Frink/g
line =~ %s/Frank/Frink/g
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=5a2a1052f8dff12596fa7f45242d25a9 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=5a2a1052f8dff12596fa7f45242d25a9 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String = "Hello world!"
Dim sString As String = "Hello world!"


Line 978: Line 978:
Print sString
Print sString


End </lang>
End </syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 990: Line 990:
<br />
<br />
Replacement:<br />
Replacement:<br />
<lang genexus>&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim!
<syntaxhighlight lang="genexus">&string = &string.ReplaceRegEx("^\s+|\s+$", "") // it's a trim!
&string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups</lang>
&string = &string.ReplaceRegEx("Another (Match)", "Replacing $1") // Using replace groups</syntaxhighlight>
Check match:
Check match:
<lang genexus>If (&string.IsMatch("regex$"))
<syntaxhighlight lang="genexus">If (&string.IsMatch("regex$"))
// The string ends with "regex"
// The string ends with "regex"
EndIf</lang>
EndIf</syntaxhighlight>
Split RegEx:
Split RegEx:
<lang genexus>&stringCollection = &string.SplitRegEx("^\d{2,4}")</lang>
<syntaxhighlight lang="genexus">&stringCollection = &string.SplitRegEx("^\d{2,4}")</syntaxhighlight>
Matches:
Matches:
<lang genexus>&RegExMatchCollection = &string.Matches("(pa)tt(ern)")
<syntaxhighlight lang="genexus">&RegExMatchCollection = &string.Matches("(pa)tt(ern)")
For &RegExMatch In &RegExMatchCollection
For &RegExMatch In &RegExMatchCollection
&FullMatch = &RegExMatch.Value // &FullMatch contains the full pattern match: "pattern"
&FullMatch = &RegExMatch.Value // &FullMatch contains the full pattern match: "pattern"
Line 1,005: Line 1,005:
// &matchVarchar contains group matches: "pa", "ern"
// &matchVarchar contains group matches: "pa", "ern"
EndFor
EndFor
EndFor</lang>
EndFor</syntaxhighlight>
Flags: <br />
Flags: <br />
s - Dot matches all (including newline) <br />
s - Dot matches all (including newline) <br />
Line 1,012: Line 1,012:
Using Flags Sintax: (?flags)pattern <br />
Using Flags Sintax: (?flags)pattern <br />
Example:<br />
Example:<br />
<lang genexus>&string = &string.ReplaceRegEx("(?si)IgnoreCase.+$", "") // Flags s and i</lang>
<syntaxhighlight lang="genexus">&string = &string.ReplaceRegEx("(?si)IgnoreCase.+$", "") // Flags s and i</syntaxhighlight>
Error Handling:
Error Handling:
<lang genexus>&string = "abc"
<syntaxhighlight lang="genexus">&string = "abc"
&RegExMatchCollection = &string.Matches("[z-a]") // invalid pattern: z-a
&RegExMatchCollection = &string.Matches("[z-a]") // invalid pattern: z-a
&errCode = RegEx.GetLastErrCode() // returns 0 if no error and 1 if an error has occured
&errCode = RegEx.GetLastErrCode() // returns 0 if no error and 1 if an error has occured
&errDsc = RegEx.GetLastErrDescription()</lang>
&errDsc = RegEx.GetLastErrDescription()</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/* Regular expressions, in Genie */
/* Regular expressions, in Genie */


Line 1,036: Line 1,036:


except err:RegexError
except err:RegexError
print err.message</lang>
print err.message</syntaxhighlight>


{{out}}
{{out}}
Line 1,045: Line 1,045:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main
import "fmt"
import "fmt"
import "regexp"
import "regexp"
Line 1,060: Line 1,060:
result := pattern.ReplaceAllString(str, "modified")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
fmt.Println(result)
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
"Matching" Solution (it's complicated):
"Matching" Solution (it's complicated):
<lang groovy>import java.util.regex.*;
<syntaxhighlight lang="groovy">import java.util.regex.*;


def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
Line 1,117: Line 1,117:


println ("'${woodchuck}' ${wwNotMatches ? 'does not' : 'does'} match '${woodRE}' exactly")
println ("'${woodchuck}' ${wwNotMatches ? 'does not' : 'does'} match '${woodRE}' exactly")
println ("'${woodchuck}' ${wwMatches ? 'does' : 'does not'} match '${containsWoodRE}' exactly")</lang>
println ("'${woodchuck}' ${wwMatches ? 'does' : 'does not'} match '${containsWoodRE}' exactly")</syntaxhighlight>


{{out}}
{{out}}
Line 1,137: Line 1,137:


Replacement Solution (String.replaceAll()):
Replacement Solution (String.replaceAll()):
<lang groovy>println woodchuck.replaceAll(/c\w+k/, "CHUCK")</lang>
<syntaxhighlight lang="groovy">println woodchuck.replaceAll(/c\w+k/, "CHUCK")</syntaxhighlight>


{{out}}
{{out}}
Line 1,143: Line 1,143:


Reusable Replacement Solution (Matcher.replaceAll()):
Reusable Replacement Solution (Matcher.replaceAll()):
<lang groovy>def ck = (woodchuck =~ /c\w+k/)
<syntaxhighlight lang="groovy">def ck = (woodchuck =~ /c\w+k/)
println (ck.replaceAll("CHUCK"))
println (ck.replaceAll("CHUCK"))
println (ck.replaceAll("wind"))
println (ck.replaceAll("wind"))
Line 1,153: Line 1,153:
println (ck.replaceAll("man"))
println (ck.replaceAll("man"))
println (ck.replaceAll("work"))
println (ck.replaceAll("work"))
println (ck.replaceAll("pickle"))</lang>
println (ck.replaceAll("pickle"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,169: Line 1,169:
=={{header|Haskell}}==
=={{header|Haskell}}==
Test
Test
<lang haskell>import Text.Regex
<syntaxhighlight lang="haskell">import Text.Regex


str = "I am a string"
str = "I am a string"
Line 1,175: Line 1,175:
case matchRegex (mkRegex ".*string$") str of
case matchRegex (mkRegex ".*string$") str of
Just _ -> putStrLn $ "ends with 'string'"
Just _ -> putStrLn $ "ends with 'string'"
Nothing -> return ()</lang>
Nothing -> return ()</syntaxhighlight>


Substitute
Substitute
<lang haskell>import Text.Regex
<syntaxhighlight lang="haskell">import Text.Regex


orig = "I am the original string"
orig = "I am the original string"
result = subRegex (mkRegex "original") orig "modified"
result = subRegex (mkRegex "original") orig "modified"
putStrLn $ result</lang>
putStrLn $ result</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" /
<syntaxhighlight lang="hicest">CHARACTER string*100/ "The quick brown fox jumps over the lazy dog" /
REAL, PARAMETER :: Regex=128, Count=256
REAL, PARAMETER :: Regex=128, Count=256


Line 1,191: Line 1,191:


vocals_changed = EDIT(Text=string, Option=Regex, Right="[aeiou]", RePLaceby='**', DO=LEN(string) ) ! changes 11
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</lang>
WRITE(ClipBoard) string ! Th** q****ck br**wn f**x j**mps **v**r th** l**zy d**g</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,198: Line 1,198:
Additionally, there is a regular expression pattern compiler 'RePat' and other supporting functions and variables.
Additionally, there is a regular expression pattern compiler 'RePat' and other supporting functions and variables.


<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()


s := "A simple string"
s := "A simple string"
Line 1,209: Line 1,209:
end
end


link regexp # link to IPL regexp </lang>
link regexp # link to IPL regexp </syntaxhighlight>
{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/procs/regexp.htm See regexp].
[http://www.cs.arizona.edu/icon/library/procs/regexp.htm See regexp].
Line 1,220: Line 1,220:
Inform's regex support is similar to Perl's but with some limitations: angle brackets are used instead of square brackets, there is no multiline mode, several control characters and character classes are omitted, and backtracking is slightly less powerful.
Inform's regex support is similar to Perl's but with some limitations: angle brackets are used instead of square brackets, there is no multiline mode, several control characters and character classes are omitted, and backtracking is slightly less powerful.


<lang inform7>let T be indexed text;
<syntaxhighlight lang="inform7">let T be indexed text;
let T be "A simple string";
let T be "A simple string";
if T matches the regular expression ".*string$", say "ends with string.";
if T matches the regular expression ".*string$", say "ends with string.";
replace the regular expression "simple" in T with "replacement";</lang>
replace the regular expression "simple" in T with "replacement";</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,229: Line 1,229:
J's regex support is built on top of PCRE.
J's regex support is built on top of PCRE.


<lang j>load'regex' NB. Load regex library
<syntaxhighlight lang="j">load'regex' NB. Load regex library
str =: 'I am a string' NB. String used in examples.</lang>
str =: 'I am a string' NB. String used in examples.</syntaxhighlight>


Matching:
Matching:
<lang j> '.*string$' rxeq str NB. 1 is true, 0 is false
<syntaxhighlight lang="j"> '.*string$' rxeq str NB. 1 is true, 0 is false
1</lang>
1</syntaxhighlight>


Substitution:
Substitution:
<lang j> ('am';'am still') rxrplc str
<syntaxhighlight lang="j"> ('am';'am still') rxrplc str
I am still a string</lang>
I am still a string</syntaxhighlight>


Note: use<lang J> open'regex'</lang> to read the source code for the library. The comments list 6 main definitions and a dozen utility definitions.
Note: use<syntaxhighlight lang="j"> open'regex'</syntaxhighlight> to read the source code for the library. The comments list 6 main definitions and a dozen utility definitions.


=={{header|Java}}==
=={{header|Java}}==
Line 1,248: Line 1,248:
Test
Test


<lang java>String str = "I am a string";
<syntaxhighlight lang="java">String str = "I am a string";
if (str.matches(".*string")) { // note: matches() tests if the entire string is a match
if (str.matches(".*string")) { // note: matches() tests if the entire string is a match
System.out.println("ends with 'string'");
System.out.println("ends with 'string'");
}</lang>
}</syntaxhighlight>


To match part of a string, or to process matches:
To match part of a string, or to process matches:
<lang java>import java.util.regex.*;
<syntaxhighlight lang="java">import java.util.regex.*;
Pattern p = Pattern.compile("a*b");
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher(str);
Matcher m = p.matcher(str);
while (m.find()) {
while (m.find()) {
// use m.group() to extract matches
// use m.group() to extract matches
}</lang>
}</syntaxhighlight>


Substitute
Substitute


<lang java>String orig = "I am the original string";
<syntaxhighlight lang="java">String orig = "I am the original string";
String result = orig.replaceAll("original", "modified");
String result = orig.replaceAll("original", "modified");
// result is now "I am the modified string"</lang>
// result is now "I am the modified string"</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Test/Match
Test/Match
<lang javascript>var subject = "Hello world!";
<syntaxhighlight lang="javascript">var subject = "Hello world!";


// Two different ways to create the RegExp object
// Two different ways to create the RegExp object
Line 1,283: Line 1,283:
// matches[0] == "Hello world"
// matches[0] == "Hello world"
// matches[1] == "world"
// matches[1] == "world"
var matches = re_PatternToMatch2.exec(subject);</lang>
var matches = re_PatternToMatch2.exec(subject);</syntaxhighlight>


Substitute
Substitute
<lang javascript>var subject = "Hello world!";
<syntaxhighlight lang="javascript">var subject = "Hello world!";


// Perform a string replacement
// Perform a string replacement
// newSubject == "Replaced!"
// newSubject == "Replaced!"
var newSubject = subject.replace(re_PatternToMatch, "Replaced");</lang>
var newSubject = subject.replace(re_PatternToMatch, "Replaced");</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,298: Line 1,298:


'''Test''':
'''Test''':
<lang jq>"I am a string" | test("string$") </lang>
<syntaxhighlight lang="jq">"I am a string" | test("string$") </syntaxhighlight>
yields: true
yields: true


'''Substitutution''':
'''Substitutution''':
<lang jq>"I am a string" | sub(" a "; " another ")</lang>
<syntaxhighlight lang="jq">"I am a string" | sub(" a "; " another ")</syntaxhighlight>
yields: "I am another string"
yields: "I am another string"


'''Substitution using capture''':
'''Substitution using capture''':
<lang jq>"abc" | sub( "(?<head>^.)(?<tail>.*)"; "\(.head)-\(.tail)")</lang>
<syntaxhighlight lang="jq">"abc" | sub( "(?<head>^.)(?<tail>.*)"; "\(.head)-\(.tail)")</syntaxhighlight>
yields: "a-bc"
yields: "a-bc"


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Regular expressions, in Jsish */
<syntaxhighlight lang="javascript">/* Regular expressions, in Jsish */


var re = /s[ai]mple/;
var re = /s[ai]mple/;
Line 1,319: Line 1,319:


var replaced = sentence.replace(re, "different");
var replaced = sentence.replace(re, "different");
printf("replaced sentence is: %s\n", replaced);</lang>
printf("replaced sentence is: %s\n", replaced);</syntaxhighlight>


{{out}}
{{out}}
Line 1,329: Line 1,329:
{{trans|Perl}}
{{trans|Perl}}
Julia implements Perl-compatible regular expressions (via the built-in [http://www.pcre.org/ PCRE library]). To test for a match:
Julia implements Perl-compatible regular expressions (via the built-in [http://www.pcre.org/ PCRE library]). To test for a match:
<lang julia>s = "I am a string"
<syntaxhighlight lang="julia">s = "I am a string"
if ismatch(r"string$", s)
if ismatch(r"string$", s)
println("'$s' ends with 'string'")
println("'$s' ends with 'string'")
end</lang>
end</syntaxhighlight>
To perform replacements:
To perform replacements:
<lang julia>s = "I am a string"
<syntaxhighlight lang="julia">s = "I am a string"
s = replace(s, r" (a|an) ", " another ")</lang>
s = replace(s, r" (a|an) ", " another ")</syntaxhighlight>
There are many [http://docs.julialang.org/en/latest/manual/strings/#regular-expressions other features] of Julia's regular-expression support, too numerous to list here.
There are many [http://docs.julialang.org/en/latest/manual/strings/#regular-expressions other features] of Julia's regular-expression support, too numerous to list here.


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,349: Line 1,349:
val s2 = s1.replace(r2, s3)
val s2 = s1.replace(r2, s3)
if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,363: Line 1,363:


To match a string, ...
To match a string, ...
<lang langur>if matching(re/abc/, "somestring") { ... }</lang>
<syntaxhighlight lang="langur">if matching(re/abc/, "somestring") { ... }</syntaxhighlight>


Or...
Or...
{{works with|langur|0.10}}
{{works with|langur|0.10}}
<lang langur>if val .x, .y = submatch(re/(abc+).+?(def)/, "somestring") { ... }</lang>
<syntaxhighlight lang="langur">if val .x, .y = submatch(re/(abc+).+?(def)/, "somestring") { ... }</syntaxhighlight>


Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.
Prior to 0.10, multi-variable declaration/assignment would use parentheses around variable names and values.
<lang langur>if val (.x, .y) = submatch(re/(abc+).+?(def)/, "somestring") { ... }</lang>
<syntaxhighlight lang="langur">if val (.x, .y) = submatch(re/(abc+).+?(def)/, "somestring") { ... }</syntaxhighlight>


Or...
Or...
<lang langur>given "somestring" {
<syntaxhighlight lang="langur">given "somestring" {
case re/abc/: ...
case re/abc/: ...
...
...
}</lang>
}</syntaxhighlight>


Or...
Or...
<lang langur>given re/abc/ {
<syntaxhighlight lang="langur">given re/abc/ {
case "somestring": ...
case "somestring": ...
...
...
}</lang>
}</syntaxhighlight>


Substitution does not alter the original string.
Substitution does not alter the original string.
<lang langur>replace("abcdef", re/abc/, "Y")
<syntaxhighlight lang="langur">replace("abcdef", re/abc/, "Y")
# result: "Ydef"</lang>
# result: "Ydef"</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
Lasso has built in support for regular expressions using ICU regexps.
Lasso has built in support for regular expressions using ICU regexps.
<lang Lasso>local(mytext = 'My name is: Stone, Rosetta
<syntaxhighlight lang="lasso">local(mytext = 'My name is: Stone, Rosetta
My name is: Hippo, Campus
My name is: Hippo, Campus
')
')
Line 1,411: Line 1,411:
#regexp -> reset(-input = #mytext)
#regexp -> reset(-input = #mytext)
'<br />'
'<br />'
#regexp -> replaceall</lang>
#regexp -> replaceall</syntaxhighlight>
<pre>Rosetta
<pre>Rosetta
Campus
Campus
Line 1,421: Line 1,421:
In Lua many string manipulation methods use ''patterns'', which offer almost the same fucntionality as regular expressions, but whose syntax differs slightly. The percent sign (<code>%</code>) is generally used instead of a backslash to start a character class or a reference for a match in a substitution.
In Lua many string manipulation methods use ''patterns'', which offer almost the same fucntionality as regular expressions, but whose syntax differs slightly. The percent sign (<code>%</code>) is generally used instead of a backslash to start a character class or a reference for a match in a substitution.


<lang lua>test = "My name is Lua."
<syntaxhighlight lang="lua">test = "My name is Lua."
pattern = ".*name is (%a*).*"
pattern = ".*name is (%a*).*"


Line 1,429: Line 1,429:


sub, num_matches = test:gsub(pattern, "Hello, %1!")
sub, num_matches = test:gsub(pattern, "Hello, %1!")
print(sub)</lang>
print(sub)</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,443: Line 1,443:
Enumerators for some COM objects are number of function -4&, we can use this in place of string for the name of property.
Enumerators for some COM objects are number of function -4&, we can use this in place of string for the name of property.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
declare global ObjRegEx "VBscript.RegExp"
declare global ObjRegEx "VBscript.RegExp"
Line 1,517: Line 1,517:
}
}
Internal
Internal
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>regexp(`GNUs not Unix', `\<[a-z]\w+')
<syntaxhighlight lang="m4">regexp(`GNUs not Unix', `\<[a-z]\w+')
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')</lang>
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')</syntaxhighlight>


{{out}}
{{out}}
Line 1,530: Line 1,530:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>#Examples from Maple Help
<syntaxhighlight lang="maple">#Examples from Maple Help
StringTools:-RegMatch("^ab+bc$", "abbbbc");
StringTools:-RegMatch("^ab+bc$", "abbbbc");
StringTools:-RegMatch("^ab+bc$", "abbbbcx");
StringTools:-RegMatch("^ab+bc$", "abbbbcx");
StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2");
StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2");
StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");</lang>
StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3");</syntaxhighlight>
{{Out|Output}}
{{Out|Output}}
<pre>true
<pre>true
Line 1,542: Line 1,542:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]]
<syntaxhighlight lang="mathematica">StringCases["I am a string with the number 18374 in me",RegularExpression["[0-9]+"]]
StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]</lang>
StringReplace["I am a string",RegularExpression["I\\sam"] -> "I'm"]</syntaxhighlight>
The in-notebook output, in order:
The in-notebook output, in order:
<pre>{18374}
<pre>{18374}
Line 1,549: Line 1,549:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
samples = #("Some string 123","Example text 123","string",\
samples = #("Some string 123","Example text 123","string",\
"ThisString Will Not Match","A123,333,string","123451")
"ThisString Will Not Match","A123,333,string","123451")
Line 1,589: Line 1,589:
)
)
)
)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,611: Line 1,611:


=={{header|MIRC Scripting Language}}==
=={{header|MIRC Scripting Language}}==
<lang mirc>alias regular_expressions {
<syntaxhighlight lang="mirc">alias regular_expressions {
var %string = This is a string
var %string = This is a string
var %re = string$
var %re = string$
Line 1,623: Line 1,623:
%re = \b(another)\b
%re = \b(another)\b
echo -a Result 2: $regsubex(%string,%re,yet \1)
echo -a Result 2: $regsubex(%string,%re,yet \1)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,633: Line 1,633:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<p>MUMPS doesn't have a replacement functionality when using the pattern matching operator, ?. We can mimic it with $PIECE, but $PIECE doesn't work with regular expressions as an operand.</p><lang MUMPS>REGEXP
<p>MUMPS doesn't have a replacement functionality when using the pattern matching operator, ?. We can mimic it with $PIECE, but $PIECE doesn't work with regular expressions as an operand.</p><syntaxhighlight lang="mumps">REGEXP
NEW HI,W,PATTERN,BOOLEAN
NEW HI,W,PATTERN,BOOLEAN
SET HI="Hello, world!",W="world"
SET HI="Hello, world!",W="world"
Line 1,645: Line 1,645:
SET BOOLEAN=$FIND(HI,W)
SET BOOLEAN=$FIND(HI,W)
IF BOOLEAN>0 WRITE $PIECE(HI,W,1)_"string"_$PIECE(HI,W,2)
IF BOOLEAN>0 WRITE $PIECE(HI,W,1)_"string"_$PIECE(HI,W,2)
QUIT</lang>
QUIT</syntaxhighlight>
Usage:<pre>
Usage:<pre>
USER>D REGEXP^ROSETTA
USER>D REGEXP^ROSETTA
Line 1,655: Line 1,655:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,692: Line 1,692:


return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,709: Line 1,709:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP >(regex "[bB]+" "AbBBbABbBAAAA") -> ("bBBb" 1 4)</lang>
<syntaxhighlight lang="newlisp ">(regex "[bB]+" "AbBBbABbBAAAA") -> ("bBBb" 1 4)</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import re
<syntaxhighlight lang="nim">import re


var s = "This is a string"
var s = "This is a string"
Line 1,720: Line 1,720:


s = s.replace(re"\ a\ ", " another ")
s = s.replace(re"\ a\ ", " another ")
echo s</lang>
echo s</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use RegEx;
use RegEx;


Line 1,741: Line 1,741:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,747: Line 1,747:
{{works with|Mac OS X|10.4+}}
{{works with|Mac OS X|10.4+}}
{{works with|iOS|3.0+}}
{{works with|iOS|3.0+}}
<lang objc>NSString *str = @"I am a string";
<syntaxhighlight lang="objc">NSString *str = @"I am a string";
NSString *regex = @".*string$";
NSString *regex = @".*string$";


Line 1,755: Line 1,755:
if ([pred evaluateWithObject:str]) {
if ([pred evaluateWithObject:str]) {
NSLog(@"ends with 'string'");
NSLog(@"ends with 'string'");
}</lang>
}</syntaxhighlight>
Unfortunately this method cannot find the location of the match or do substitution.
Unfortunately this method cannot find the location of the match or do substitution.


Line 1,762: Line 1,762:
{{works with|Mac OS X|10.7+}}
{{works with|Mac OS X|10.7+}}
{{works with|iOS|3.2+}}
{{works with|iOS|3.2+}}
<lang objc>NSString *str = @"I am a string";
<syntaxhighlight lang="objc">NSString *str = @"I am a string";
if ([str rangeOfString:@"string$" options:NSRegularExpressionSearch].location != NSNotFound) {
if ([str rangeOfString:@"string$" options:NSRegularExpressionSearch].location != NSNotFound) {
NSLog(@"Ends with 'string'");
NSLog(@"Ends with 'string'");
}</lang>
}</syntaxhighlight>


Substitute
Substitute
{{works with|Mac OS X|10.7+}}
{{works with|Mac OS X|10.7+}}
{{works with|iOS|4.0+}} undocumented
{{works with|iOS|4.0+}} undocumented
<lang objc>NSString *orig = @"I am the original string";
<syntaxhighlight lang="objc">NSString *orig = @"I am the original string";
NSString *result = [orig stringByReplacingOccurrencesOfString:@"original"
NSString *result = [orig stringByReplacingOccurrencesOfString:@"original"
withString:@"modified"
withString:@"modified"
options:NSRegularExpressionSearch
options:NSRegularExpressionSearch
range:NSMakeRange(0, [orig length])];
range:NSMakeRange(0, [orig length])];
NSLog(@"%@", result);</lang>
NSLog(@"%@", result);</syntaxhighlight>


===NSRegularExpression===
===NSRegularExpression===
Line 1,781: Line 1,781:
{{works with|iOS|4.0+}}
{{works with|iOS|4.0+}}
Test
Test
<lang objc>NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"string$"
<syntaxhighlight lang="objc">NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"string$"
options:0
options:0
error:NULL];
error:NULL];
Line 1,790: Line 1,790:
].location != NSNotFound) {
].location != NSNotFound) {
NSLog(@"Ends with 'string'");
NSLog(@"Ends with 'string'");
}</lang>
}</syntaxhighlight>


Loop through matches
Loop through matches
<lang objc>for (NSTextCheckingResult *match in [regex matchesInString:str
<syntaxhighlight lang="objc">for (NSTextCheckingResult *match in [regex matchesInString:str
options:0
options:0
range:NSMakeRange(0, [str length])
range:NSMakeRange(0, [str length])
Line 1,799: Line 1,799:
// match.range gives the range of the whole match
// match.range gives the range of the whole match
// [match rangeAtIndex:i] gives the range of the i'th capture group (starting from 1)
// [match rangeAtIndex:i] gives the range of the i'th capture group (starting from 1)
}</lang>
}</syntaxhighlight>


Substitute
Substitute
<lang objc>NSString *orig = @"I am the original string";
<syntaxhighlight lang="objc">NSString *orig = @"I am the original string";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"original"
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"original"
options:0
options:0
Line 1,810: Line 1,810:
range:NSMakeRange(0, [orig length])
range:NSMakeRange(0, [orig length])
withTemplate:@"modified"];
withTemplate:@"modified"];
NSLog(@"%@", result);</lang>
NSLog(@"%@", result);</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
=== With the standard library ===
=== With the standard library ===
Test
Test
<lang ocaml>#load "str.cma";;
<syntaxhighlight lang="ocaml">#load "str.cma";;
let str = "I am a string";;
let str = "I am a string";;
try
try
Line 1,821: Line 1,821:
print_endline "ends with 'string'"
print_endline "ends with 'string'"
with Not_found -> ()
with Not_found -> ()
;;</lang>
;;</syntaxhighlight>


Substitute
Substitute
<lang ocaml>#load "str.cma";;
<syntaxhighlight lang="ocaml">#load "str.cma";;
let orig = "I am the original string";;
let orig = "I am the original string";;
let result = Str.global_replace (Str.regexp "original") "modified" orig;;
let result = Str.global_replace (Str.regexp "original") "modified" orig;;
(* result is now "I am the modified string" *)</lang>
(* result is now "I am the modified string" *)</syntaxhighlight>


=== Using Pcre ===
=== Using Pcre ===
'''Library:''' [http://ocaml.info/home/ocaml_sources.html#pcre-ocaml ocaml-pcre]
'''Library:''' [http://ocaml.info/home/ocaml_sources.html#pcre-ocaml ocaml-pcre]


<lang ocaml>let matched pat str =
<syntaxhighlight lang="ocaml">let matched pat str =
try ignore(Pcre.exec ~pat str); (true)
try ignore(Pcre.exec ~pat str); (true)
with Not_found -> (false)
with Not_found -> (false)
Line 1,841: Line 1,841:
Printf.printf "Substitute: %s\n"
Printf.printf "Substitute: %s\n"
(Pcre.replace ~pat:"original" ~templ:"modified" "I am the original string")
(Pcre.replace ~pat:"original" ~templ:"modified" "I am the original string")
;;</lang>
;;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
; matching:
; matching:
(define regex (string->regex "m/aa(bb|cc)dd/"))
(define regex (string->regex "m/aa(bb|cc)dd/"))
Line 1,857: Line 1,857:
(print (regex "aabcddx")) ; => false
(print (regex "aabcddx")) ; => false


</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
/* Using the RxRegExp Regular Expression built-in utility class */
/* Using the RxRegExp Regular Expression built-in utility class */


Line 1,902: Line 1,902:


::requires "rxregexp.cls"
::requires "rxregexp.cls"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,912: Line 1,912:


=={{header|Oxygene}}==
=={{header|Oxygene}}==
<lang oxygene>
<syntaxhighlight lang="oxygene">
// Match and Replace part of a string using a Regular Expression
// Match and Replace part of a string using a Regular Expression
//
//
Line 1,943: Line 1,943:
end.
end.
</syntaxhighlight>
</lang>
Produces:
Produces:
<pre>
<pre>
Line 1,951: Line 1,951:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
[Regex] = {Module.link ['x-oz://contrib/regex']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
String = "This is a string"
String = "This is a string"
Line 1,958: Line 1,958:
{System.showInfo "Ends with string."}
{System.showInfo "Ends with string."}
end
end
{System.showInfo {Regex.replace String " a " fun {$ _ _} " another " end}}</lang>
{System.showInfo {Regex.replace String " a " fun {$ _ _} " another " end}}</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>
<syntaxhighlight lang="pascal">
// Match and Replace part of a string using a Regular Expression
// Match and Replace part of a string using a Regular Expression
//
//
Line 1,987: Line 1,987:
if r.Exec(myResult) then writeln(' contains ' + r.Match[0]);
if r.Exec(myResult) then writeln(' contains ' + r.Match[0]);
end.
end.
</syntaxhighlight>
</lang>
Produces:
Produces:
<pre>
<pre>
Line 1,998: Line 1,998:
{{works with|Perl|5.8.8}}
{{works with|Perl|5.8.8}}
Test
Test
<lang perl>$string = "I am a string";
<syntaxhighlight lang="perl">$string = "I am a string";
if ($string =~ /string$/) {
if ($string =~ /string$/) {
print "Ends with 'string'\n";
print "Ends with 'string'\n";
Line 2,005: Line 2,005:
if ($string !~ /^You/) {
if ($string !~ /^You/) {
print "Does not start with 'You'\n";
print "Does not start with 'You'\n";
}</lang>
}</syntaxhighlight>




Substitute
Substitute
<lang perl>$string = "I am a string";
<syntaxhighlight lang="perl">$string = "I am a string";
$string =~ s/ a / another /; # makes "I am a string" into "I am another string"
$string =~ s/ a / another /; # makes "I am a string" into "I am another string"
print $string;</lang>
print $string;</syntaxhighlight>


In Perl 5.14+, you can return a new substituted string without altering the original string:
In Perl 5.14+, you can return a new substituted string without altering the original string:
<lang perl>$string = "I am a string";
<syntaxhighlight lang="perl">$string = "I am a string";
$string2 = $string =~ s/ a / another /r; # $string2 == "I am another string", $string is unaltered
$string2 = $string =~ s/ a / another /r; # $string2 == "I am another string", $string is unaltered
print $string2;</lang>
print $string2;</syntaxhighlight>




Test and Substitute
Test and Substitute
<lang perl>$string = "I am a string";
<syntaxhighlight lang="perl">$string = "I am a string";
if ($string =~ s/\bam\b/was/) { # \b is a word border
if ($string =~ s/\bam\b/was/) { # \b is a word border
print "I was able to find and replace 'am' with 'was'\n";
print "I was able to find and replace 'am' with 'was'\n";
}</lang>
}</syntaxhighlight>




Options
Options
<lang perl># add the following just after the last / for additional control
<syntaxhighlight lang="perl"># add the following just after the last / for additional control
# g = globally (match as many as possible)
# g = globally (match as many as possible)
# i = case-insensitive
# i = case-insensitive
Line 2,033: Line 2,033:
# m = multi-line (the expression is run on each line individually)
# m = multi-line (the expression is run on each line individually)


$string =~ s/i/u/ig; # would change "I am a string" into "u am a strung"</lang>
$string =~ s/i/u/ig; # would change "I am a string" into "u am a strung"</syntaxhighlight>


Omission of the regular expression binding operators
Omission of the regular expression binding operators
Line 2,039: Line 2,039:
If regular expression matches are being made against the topic variable, it is possible to omit the regular expression binding operators:
If regular expression matches are being made against the topic variable, it is possible to omit the regular expression binding operators:


<lang perl>$_ = "I like banana milkshake.";
<syntaxhighlight lang="perl">$_ = "I like banana milkshake.";
if (/banana/) { # The regular expression binding operator is omitted
if (/banana/) { # The regular expression binding operator is omitted
print "Match found\n";
print "Match found\n";
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">regex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">regex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,058: Line 2,058:
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">gsub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`\ba\b`</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"another"</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">gsub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`\ba\b`</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"another"</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">gsub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`string`</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"replacement"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">gsub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`string`</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"replacement"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,073: Line 2,073:
=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|5.2.0}}
{{works with|PHP|5.2.0}}
<lang php>$string = 'I am a string';
<syntaxhighlight lang="php">$string = 'I am a string';
# Test
# Test
if (preg_match('/string$/', $string))
if (preg_match('/string$/', $string))
Line 2,081: Line 2,081:
# Replace
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";</lang>
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";</syntaxhighlight>


{{out}}
{{out}}
Line 2,091: Line 2,091:
PicoLisp doesn't have built-in regex functionality.
PicoLisp doesn't have built-in regex functionality.
It is easy to call the native C library.
It is easy to call the native C library.
<lang PicoLisp>(let (Pat "a[0-9]z" String "a7z")
<syntaxhighlight lang="picolisp">(let (Pat "a[0-9]z" String "a7z")
(use Preg
(use Preg
(native "@" "regcomp" 'I '(Preg (64 B . 64)) Pat 1) # Compile regex
(native "@" "regcomp" 'I '(Preg (64 B . 64)) Pat 1) # Compile regex
(when (=0 (native "@" "regexec" 'I (cons NIL (64) Preg) String 0 0 0))
(when (=0 (native "@" "regexec" 'I (cons NIL (64) Preg) String 0 0 0))
(prinl "String \"" String "\" matches regex \"" Pat "\"") ) ) )</lang>
(prinl "String \"" String "\" matches regex \"" Pat "\"") ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>String "a7z" matches pattern "a[0-9]z"</pre>
<pre>String "a7z" matches pattern "a[0-9]z"</pre>
Line 2,103: Line 2,103:
Another possibility is dynamic pattern matching,
Another possibility is dynamic pattern matching,
where arbitrary conditions can be programmed.
where arbitrary conditions can be programmed.
<lang PicoLisp>(let String "The number <7> is incremented"
<syntaxhighlight lang="picolisp">(let String "The number <7> is incremented"
(use (@A @N @Z)
(use (@A @N @Z)
(and
(and
(match '(@A "<" @N ">" @Z) (chop String))
(match '(@A "<" @N ">" @Z) (chop String))
(format @N)
(format @N)
(prinl @A "<" (inc @) ">" @Z) ) ) )</lang>
(prinl @A "<" (inc @) ">" @Z) ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>The number <8> is incremented</pre>
<pre>The number <8> is incremented</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>"I am a string" -match '\bstr' # true
<syntaxhighlight lang="powershell">"I am a string" -match '\bstr' # true
"I am a string" -replace 'a\b','no' # I am no string</lang>
"I am a string" -replace 'a\b','no' # I am no string</syntaxhighlight>
By default both the <code>-match</code> and <code>-replace</code> operators are case-insensitive. They can be made case-sensitive by using the <code>-cmatch</code> and <code>-creplace</code> operators.
By default both the <code>-match</code> and <code>-replace</code> operators are case-insensitive. They can be made case-sensitive by using the <code>-cmatch</code> and <code>-creplace</code> operators.


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>String$ = "<tag>some text consisting of Roman letters spaces and numbers like 12</tag>"
<syntaxhighlight lang="purebasic">String$ = "<tag>some text consisting of Roman letters spaces and numbers like 12</tag>"
regex$ = "<([a-z]*)>[a-z,A-Z,0-9, ]*</\1>"
regex$ = "<([a-z]*)>[a-z,A-Z,0-9, ]*</\1>"
regex_replace$ = "letters[a-z,A-Z,0-9, ]*numbers[a-z,A-Z,0-9, ]*"
regex_replace$ = "letters[a-z,A-Z,0-9, ]*numbers[a-z,A-Z,0-9, ]*"
Line 2,126: Line 2,126:
EndIf
EndIf
Debug ReplaceRegularExpression(2, String$, "char stuff")
Debug ReplaceRegularExpression(2, String$, "char stuff")
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import re
<syntaxhighlight lang="python">import re


string = "This is a string"
string = "This is a string"
Line 2,137: Line 2,137:


string = re.sub(" a ", " another ", string)
string = re.sub(" a ", " another ", string)
print(string)</lang>
print(string)</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
First, define some strings.
First, define some strings.
<lang R>pattern <- "string"
<syntaxhighlight lang="r">pattern <- "string"
text1 <- "this is a matching string"
text1 <- "this is a matching string"
text2 <- "this does not match"</lang>
text2 <- "this does not match"</syntaxhighlight>
Matching with grep. The indices of the texts containing matches are returned.
Matching with grep. The indices of the texts containing matches are returned.
<lang R>grep(pattern, c(text1, text2)) # 1</lang>
<syntaxhighlight lang="r">grep(pattern, c(text1, text2)) # 1</syntaxhighlight>
Matching with regexpr. The positions of the starts of the matches are returned, along with the lengths of the matches.
Matching with regexpr. The positions of the starts of the matches are returned, along with the lengths of the matches.
<lang R>regexpr(pattern, c(text1, text2))</lang>
<syntaxhighlight lang="r">regexpr(pattern, c(text1, text2))</syntaxhighlight>
[1] 20 -1
[1] 20 -1
attr(,"match.length")
attr(,"match.length")
[1] 6 -1
[1] 6 -1
Replacement
Replacement
<lang R>gsub(pattern, "pair of socks", c(text1, text2))</lang>
<syntaxhighlight lang="r">gsub(pattern, "pair of socks", c(text1, text2))</syntaxhighlight>
[1] "this is a matching pair of socks" "this does not match"
[1] "this is a matching pair of socks" "this does not match"


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,169: Line 2,169:


(displayln (regexp-replace " a " s " another "))
(displayln (regexp-replace " a " s " another "))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>if 'a long string' ~~ /string$/ {
<syntaxhighlight lang="raku" line>if 'a long string' ~~ /string$/ {
say "It ends with 'string'";
say "It ends with 'string'";
}
}
Line 2,184: Line 2,184:
# output:
# output:
# Xxx xxx Xxx xxx
# Xxx xxx Xxx xxx
</syntaxhighlight>
</lang>


=={{header|Raven}}==
=={{header|Raven}}==


<lang raven>'i am a string' as str</lang>
<syntaxhighlight lang="raven">'i am a string' as str</syntaxhighlight>


Match:
Match:


<lang raven>str m/string$/
<syntaxhighlight lang="raven">str m/string$/
if "Ends with 'string'\n" print</lang>
if "Ends with 'string'\n" print</syntaxhighlight>


Replace once:
Replace once:


<lang raven>str r/ a / another / print</lang>
<syntaxhighlight lang="raven">str r/ a / another / print</syntaxhighlight>
<lang raven>str r/ /_/ print</lang>
<syntaxhighlight lang="raven">str r/ /_/ print</syntaxhighlight>


Replace all:
Replace all:


<lang raven>str r/ /_/g print</lang>
<syntaxhighlight lang="raven">str r/ /_/g print</syntaxhighlight>


Replace case insensitive:
Replace case insensitive:


<lang raven>str r/ A / another /i print</lang>
<syntaxhighlight lang="raven">str r/ A / another /i print</syntaxhighlight>


Splitting:
Splitting:


<lang raven>str s/ /</lang>
<syntaxhighlight lang="raven">str s/ /</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Regular Expression Matching"
Title: "Regular Expression Matching"
URL: http://rosettacode.org/wiki/Regular_expression_matching
URL: http://rosettacode.org/wiki/Regular_expression_matching
Line 2,252: Line 2,252:


replace string " another " " a " ; Change string back.
replace string " another " " a " ; Change string back.
print [crlf "Replacement:" string]</lang>
print [crlf "Replacement:" string]</syntaxhighlight>


{{out}}
{{out}}
Line 2,269: Line 2,269:


===testing===
===testing===
<lang rexx>/*REXX program demonstrates testing (modeled after Perl example).*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates testing (modeled after Perl example).*/
$string="I am a string"
$string="I am a string"
say 'The string is:' $string
say 'The string is:' $string
Line 2,276: Line 2,276:
z="ring" ; if pos(z,$string)\==0 then say 'It contains the string:' z
z="ring" ; if pos(z,$string)\==0 then say 'It contains the string:' z
z="ring" ; if wordpos(z,$string)==0 then say 'It does not contain the word:' z
z="ring" ; if wordpos(z,$string)==0 then say 'It does not contain the word:' z
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,287: Line 2,287:


===substitution &nbsp; (destructive)===
===substitution &nbsp; (destructive)===
<lang rexx>/*REXX program demonstrates substitution (modeled after Perl example).*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates substitution (modeled after Perl example).*/
$string = "I am a string"
$string = "I am a string"
old = " a "
old = " a "
Line 2,296: Line 2,296:
$string = changestr(old,$string,new)
$string = changestr(old,$string,new)
say 'The changed string is:' $string
say 'The changed string is:' $string
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,307: Line 2,307:


===substitution &nbsp; (non-destructive)===
===substitution &nbsp; (non-destructive)===
<lang rexx>/*REXX program shows non-destructive sub. (modeled after Perl example).*/
<syntaxhighlight lang="rexx">/*REXX program shows non-destructive sub. (modeled after Perl example).*/
$string = "I am a string"
$string = "I am a string"
old = " a "
old = " a "
Line 2,317: Line 2,317:
say 'The original string is:' $string
say 'The original string is:' $string
say 'The changed string is:' $string2
say 'The changed string is:' $string2
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,328: Line 2,328:


===test and substitute===
===test and substitute===
<lang rexx>/*REXX program shows test and substitute (modeled after Perl example).*/
<syntaxhighlight lang="rexx">/*REXX program shows test and substitute (modeled after Perl example).*/
$string = "I am a string"
$string = "I am a string"
old = " am "
old = " am "
Line 2,341: Line 2,341:
say 'I was able to find and replace ' old " with " new
say 'I was able to find and replace ' old " with " new
end
end
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,353: Line 2,353:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Regular expressions
# Project : Regular expressions


Line 2,363: Line 2,363:
text = left(text,i - 1) + "was" + substr(text,i + 2)
text = left(text,i - 1) + "was" + substr(text,i + 2)
see "replace 'am' with 'was' = " + text + nl
see "replace 'am' with 'was' = " + text + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,372: Line 2,372:
=={{header|Ruby}}==
=={{header|Ruby}}==
Test
Test
<lang ruby>str = "I am a string"
<syntaxhighlight lang="ruby">str = "I am a string"
p "Ends with 'string'" if str =~ /string$/
p "Ends with 'string'" if str =~ /string$/
p "Does not start with 'You'" unless str =~ /^You/</lang>
p "Does not start with 'You'" unless str =~ /^You/</syntaxhighlight>


Substitute
Substitute
<lang ruby>str.sub(/ a /, ' another ') #=> "I am another string"
<syntaxhighlight lang="ruby">str.sub(/ a /, ' another ') #=> "I am another string"
# Or:
# Or:
str[/ a /] = ' another ' #=> "another"
str[/ a /] = ' another ' #=> "another"
str #=> "I am another string"</lang>
str #=> "I am another string"</syntaxhighlight>


Substitute using block
Substitute using block
<lang ruby>str.gsub(/\bam\b/) { |match| match.upcase } #=> "I AM a string"</lang>
<syntaxhighlight lang="ruby">str.gsub(/\bam\b/) { |match| match.upcase } #=> "I AM a string"</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>string$ = "I am a string"
<syntaxhighlight lang="runbasic">string$ = "I am a string"
if right$(string$,6) = "string" then print "'";string$;"' ends with 'string'"
if right$(string$,6) = "string" then print "'";string$;"' ends with 'string'"
i = instr(string$,"am")
i = instr(string$,"am")
string$ = left$(string$,i - 1) + "was" + mid$(string$,i + 2)
string$ = left$(string$,i - 1) + "was" + mid$(string$,i + 2)
print "replace 'am' with 'was' = ";string$
print "replace 'am' with 'was' = ";string$
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>'I am a string' ends with 'string'
<pre>'I am a string' ends with 'string'
Line 2,398: Line 2,398:
=={{header|Rust}}==
=={{header|Rust}}==
Note that <code>Regex::new</code> checks for a valid regex and thus returns a <code>Result<Regex, Error></code>.
Note that <code>Regex::new</code> checks for a valid regex and thus returns a <code>Result<Regex, Error></code>.
<lang Rust>use regex::Regex;
<syntaxhighlight lang="rust">use regex::Regex;


fn main() {
fn main() {
Line 2,408: Line 2,408:


println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
Sather understands POSIX regular expressions.
Sather understands POSIX regular expressions.


<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
-- we need to implement the substitution
-- we need to implement the substitution
regex_subst(re:REGEXP, s, sb:STR):STR is
regex_subst(re:REGEXP, s, sb:STR):STR is
Line 2,434: Line 2,434:
#OUT + regex_subst(REGEXP::regexp("am +a +st", true), s, "get the ") + "\n";
#OUT + regex_subst(REGEXP::regexp("am +a +st", true), s, "get the ") + "\n";
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
Define
Define
<lang Scala>val Bottles1 = "(\\d+) bottles of beer".r // syntactic sugar
<syntaxhighlight lang="scala">val Bottles1 = "(\\d+) bottles of beer".r // syntactic sugar
val Bottles2 = """(\d+) bottles of beer""".r // using triple-quotes to preserve backslashes
val Bottles2 = """(\d+) bottles of beer""".r // using triple-quotes to preserve backslashes
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer") // standard
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer") // standard
val Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups</lang>
val Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups</syntaxhighlight>


Search and replace with string methods:
Search and replace with string methods:
<lang scala>"99 bottles of beer" matches "(\\d+) bottles of beer" // the full string must match
<syntaxhighlight lang="scala">"99 bottles of beer" matches "(\\d+) bottles of beer" // the full string must match
"99 bottles of beer" replace ("99", "98") // Single replacement
"99 bottles of beer" replace ("99", "98") // Single replacement
"99 bottles of beer" replaceAll ("b", "B") // Multiple replacement</lang>
"99 bottles of beer" replaceAll ("b", "B") // Multiple replacement</syntaxhighlight>


Search with regex methods:
Search with regex methods:
<lang scala>"\\d+".r findFirstIn "99 bottles of beer" // returns first partial match, or None
<syntaxhighlight lang="scala">"\\d+".r findFirstIn "99 bottles of beer" // returns first partial match, or None
"\\w+".r findAllIn "99 bottles of beer" // returns all partial matches as an iterator
"\\w+".r findAllIn "99 bottles of beer" // returns all partial matches as an iterator
"\\s+".r findPrefixOf "99 bottles of beer" // returns a matching prefix, or None
"\\s+".r findPrefixOf "99 bottles of beer" // returns a matching prefix, or None
Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None
Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None
Bottles4 findPrefixMatchOf "99 bottles of beer" // same thing, for prefixes
Bottles4 findPrefixMatchOf "99 bottles of beer" // same thing, for prefixes
val bottles = (Bottles4 findFirstMatchIn "99 bottles of beer").get.group("bottles") // Getting a group by name</lang>
val bottles = (Bottles4 findFirstMatchIn "99 bottles of beer").get.group("bottles") // Getting a group by name</syntaxhighlight>


Using pattern matching with regex:
Using pattern matching with regex:
<lang Scala>val Some(bottles) = Bottles4 findPrefixOf "99 bottles of beer" // throws an exception if the matching fails; full string must match
<syntaxhighlight lang="scala">val Some(bottles) = Bottles4 findPrefixOf "99 bottles of beer" // throws an exception if the matching fails; full string must match
for {
for {
line <- """|99 bottles of beer on the wall
line <- """|99 bottles of beer on the wall
Line 2,470: Line 2,470:
for {
for {
matched <- "(\\w+)".r findAllIn "99 bottles of beer" matchData // matchData converts to an Iterator of Match
matched <- "(\\w+)".r findAllIn "99 bottles of beer" matchData // matchData converts to an Iterator of Match
} println("Matched from "+matched.start+" to "+matched.end)</lang>
} println("Matched from "+matched.start+" to "+matched.end)</syntaxhighlight>


Replacing with regex:
Replacing with regex:
<lang Scala>Bottles2 replaceFirstIn ("99 bottles of beer", "98 bottles of beer")
<syntaxhighlight lang="scala">Bottles2 replaceFirstIn ("99 bottles of beer", "98 bottles of beer")
Bottles3 replaceAllIn ("99 bottles of beer", "98 bottles of beer")</lang>
Bottles3 replaceAllIn ("99 bottles of beer", "98 bottles of beer")</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==


Basic example showing the use of SenseTalk's pattern language to create a pattern, test for a match, find all matches, and replace a match.
Basic example showing the use of SenseTalk's pattern language to create a pattern, test for a match, find all matches, and replace a match.
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set text to "This is a story about R2D2 and C3P0 who are best friends."
set text to "This is a story about R2D2 and C3P0 who are best friends."
set pattern to <word start, letter, digit, letter, digit, word end>
set pattern to <word start, letter, digit, letter, digit, word end>
Line 2,489: Line 2,489:
replace the second occurrence of pattern in text with "Luke"
replace the second occurrence of pattern in text with "Luke"
put text
put text
</syntaxhighlight>
</lang>
Output
Output
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
True
True
(R2D2,C3P0)
(R2D2,C3P0)
This is a story about R2D2 and Luke who are best friends.
This is a story about R2D2 and Luke who are best friends.
</syntaxhighlight>
</lang>


Advanced example showing how to use capture groups within a pattern to reformat the names in a list.
Advanced example showing how to use capture groups within a pattern to reformat the names in a list.
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set phoneList to {{
set phoneList to {{
Harry Potter 98951212
Harry Potter 98951212
Line 2,511: Line 2,511:
replace every occurrence of namePattern in phoneList with "{:lastName}, {:firstName} –"
replace every occurrence of namePattern in phoneList with "{:lastName}, {:firstName} –"
put phoneList
put phoneList
</syntaxhighlight>
</lang>
Output
Output
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
Potter, Harry – 98951212
Potter, Harry – 98951212
Granger, Hermione – 59867125
Granger, Hermione – 59867125
Weasley, Ron – 56471832
Weasley, Ron – 56471832
</syntaxhighlight>
</lang>


=={{header|Shiny}}==
=={{header|Shiny}}==
<lang shiny>str: 'I am a string'</lang>
<syntaxhighlight lang="shiny">str: 'I am a string'</syntaxhighlight>


Match text:
Match text:
<lang shiny>if str.match ~string$~
<syntaxhighlight lang="shiny">if str.match ~string$~
say "Ends with 'string'"
say "Ends with 'string'"
end</lang>
end</syntaxhighlight>


Replace text:
Replace text:
<lang shiny>say str.alter ~ a ~ 'another'</lang>
<syntaxhighlight lang="shiny">say str.alter ~ a ~ 'another'</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Simple matching:
Simple matching:
<lang ruby>var str = "I am a string";
<syntaxhighlight lang="ruby">var str = "I am a string";
if (str =~ /string$/) {
if (str =~ /string$/) {
print "Ends with 'string'\n";
print "Ends with 'string'\n";
}</lang>
}</syntaxhighlight>


Global matching:
Global matching:
<lang ruby>var str = <<'EOF';
<syntaxhighlight lang="ruby">var str = <<'EOF';
x:Foo
x:Foo
y:Bar
y:Bar
Line 2,545: Line 2,545:
while (var m = str=~/(\w+):(\S+)/g) {
while (var m = str=~/(\w+):(\S+)/g) {
say "#{m[0]} -> #{m[1]}";
say "#{m[0]} -> #{m[1]}";
}</lang>
}</syntaxhighlight>


Substitutions:
Substitutions:
<lang ruby>var str = "I am a string";
<syntaxhighlight lang="ruby">var str = "I am a string";


# Substitute something mached by a regex
# Substitute something mached by a regex
Line 2,559: Line 2,559:
str = str.gsub(/(\w+)/, {|s1| 'x' * s1.len}); # globaly replace any word with 'xxx'
str = str.gsub(/(\w+)/, {|s1| 'x' * s1.len}); # globaly replace any word with 'xxx'


say str; # prints: 'x xx xxxxxx'</lang>
say str; # prints: 'x xx xxxxxx'</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
Line 2,565: Line 2,565:
This library is still in its early stages. There isn't currently a feature to replace a substring.
This library is still in its early stages. There isn't currently a feature to replace a substring.


<lang slate>
<syntaxhighlight lang="slate">
'http://slatelanguage.org/test/page?query' =~ '^(([^:/?#]+)\\:)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'.
'http://slatelanguage.org/test/page?query' =~ '^(([^:/?#]+)\\:)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'.


" ==> {'http:'. 'http'. '//slatelanguage.org'. 'slatelanguage.org'. '/test/page'. '?query'. 'query'. Nil} "
" ==> {'http:'. 'http'. '//slatelanguage.org'. 'slatelanguage.org'. '/test/page'. '?query'. 'query'. Nil} "
</syntaxhighlight>
</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>|re s s1|
<syntaxhighlight lang="smalltalk">|re s s1|
re := Regex fromString: '[a-z]+ing'.
re := Regex fromString: '[a-z]+ing'.
s := 'this is a matching string'.
s := 'this is a matching string'.
Line 2,591: Line 2,591:
].
].


(s replacingRegex: re with: 'modified') displayNl.</lang>
(s replacingRegex: re with: 'modified') displayNl.</syntaxhighlight>


{{works with|Pharo}}
{{works with|Pharo}}
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
|re s s1|
|re s s1|
re := 'm[a-z]+ing' asRegex.
re := 'm[a-z]+ing' asRegex.
Line 2,602: Line 2,602:
s1 := re copy: s replacingMatchesWith: 'modified'.
s1 := re copy: s replacingMatchesWith: 'modified'.
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 2,612: Line 2,612:
SNOBOL4's "raison d'etre" is pattern matching and string manipulation (although it's also strong in data structures too). The basic statement syntax in SNOBOL4 is:
SNOBOL4's "raison d'etre" is pattern matching and string manipulation (although it's also strong in data structures too). The basic statement syntax in SNOBOL4 is:


<lang snobol4>label subject pattern = object :(goto)</lang>
<syntaxhighlight lang="snobol4">label subject pattern = object :(goto)</syntaxhighlight>


The basic operation is to evaluate the subject, evaluate the pattern, find the pattern in the subject, evaluate the object, and then replace the portion of the subject matched by the pattern with the evaluated object. If any of those steps fails (i.e. does not succeed) then execution continues with the goto, as appropriate.
The basic operation is to evaluate the subject, evaluate the pattern, find the pattern in the subject, evaluate the object, and then replace the portion of the subject matched by the pattern with the evaluated object. If any of those steps fails (i.e. does not succeed) then execution continues with the goto, as appropriate.
Line 2,618: Line 2,618:
The goto can be unconditional, or can be based on whether the statement succeeded or failed (and that is the basis for all explicit transfers of control in SNOBOL4). This example finds the string "SNOBOL4" in string variable string1, and replaces it with "new SPITBOL" (SPITBOL is an implementation of SNOBOL4, basically SPITBOL is to SNOBOL4 what Turbo Pascal is to Pascal):
The goto can be unconditional, or can be based on whether the statement succeeded or failed (and that is the basis for all explicit transfers of control in SNOBOL4). This example finds the string "SNOBOL4" in string variable string1, and replaces it with "new SPITBOL" (SPITBOL is an implementation of SNOBOL4, basically SPITBOL is to SNOBOL4 what Turbo Pascal is to Pascal):


<lang snobol4> string1 = "The SNOBOL4 language is designed for string manipulation."
<syntaxhighlight lang="snobol4"> string1 = "The SNOBOL4 language is designed for string manipulation."
string1 "SNOBOL4" = "new SPITBOL" :s(changed)f(nochange)</lang>
string1 "SNOBOL4" = "new SPITBOL" :s(changed)f(nochange)</syntaxhighlight>


The following example replaces "diameter is " and a numeric value by "circumference is " and the circumference instead (it also shows creation of a pattern which matches integer or real numeric values, and storing that pattern into a variable... and then using that pattern variable later in a slightly more complicated pattern expression):
The following example replaces "diameter is " and a numeric value by "circumference is " and the circumference instead (it also shows creation of a pattern which matches integer or real numeric values, and storing that pattern into a variable... and then using that pattern variable later in a slightly more complicated pattern expression):


<lang snobol4> pi = 3.1415926
<syntaxhighlight lang="snobol4"> pi = 3.1415926
dd = "0123456789"
dd = "0123456789"
string1 = "For the first circle, the diameter is 2.5 inches."
string1 = "For the first circle, the diameter is 2.5 inches."
numpat = span(dd) (("." span(dd)) | null)
numpat = span(dd) (("." span(dd)) | null)
string1 "diameter is " numpat . diam = "circumference is " diam * pi</lang>
string1 "diameter is " numpat . diam = "circumference is " diam * pi</syntaxhighlight>


Relatively trivial pattern matching and replacements can be attacked very effectively using regular expressions, but regular expressions (while ubiquitous) are a crippling limitation for more complicated pattern matching problems.
Relatively trivial pattern matching and replacements can be attacked very effectively using regular expressions, but regular expressions (while ubiquitous) are a crippling limitation for more complicated pattern matching problems.
Line 2,635: Line 2,635:
{{works with|SML/NJ}}
{{works with|SML/NJ}}
Test
Test
<lang sml>CM.make "$/regexp-lib.cm";
<syntaxhighlight lang="sml">CM.make "$/regexp-lib.cm";
structure RE = RegExpFn (
structure RE = RegExpFn (
structure P = AwkSyntax
structure P = AwkSyntax
Line 2,648: Line 2,648:
in
in
print ("matched at position " ^ Int.toString pos ^ "\n")
print ("matched at position " ^ Int.toString pos ^ "\n")
end;</lang>
end;</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
See '''[http://www.stata.com/help.cgi?regexm regexm]''', '''regexr''' and '''regexs''' in Stata help.
See '''[http://www.stata.com/help.cgi?regexm regexm]''', '''regexr''' and '''regexs''' in Stata help.


<lang stata>scalar s="ars longa vita brevis"
<syntaxhighlight lang="stata">scalar s="ars longa vita brevis"


* is there a vowel?
* is there a vowel?
Line 2,659: Line 2,659:


* replace the first vowel with "?"
* replace the first vowel with "?"
di regexr(s,"[aeiou]","?")</lang>
di regexr(s,"[aeiou]","?")</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Line 2,665: Line 2,665:
===RegularExpressionSearch===
===RegularExpressionSearch===
Test
Test
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let str = "I am a string"
let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
println("Ends with 'string'")
println("Ends with 'string'")
}</lang>
}</syntaxhighlight>


Substitute (undocumented)
Substitute (undocumented)
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let orig = "I am the original string"
let orig = "I am the original string"
let result = orig.stringByReplacingOccurrencesOfString("original", withString: "modified", options: .RegularExpressionSearch)
let result = orig.stringByReplacingOccurrencesOfString("original", withString: "modified", options: .RegularExpressionSearch)
println(result)</lang>
println(result)</syntaxhighlight>


===NSRegularExpression===
===NSRegularExpression===
Test
Test
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


if let regex = NSRegularExpression(pattern: "string$", options: nil, error: nil) {
if let regex = NSRegularExpression(pattern: "string$", options: nil, error: nil) {
Line 2,688: Line 2,688:
println("Ends with 'string'")
println("Ends with 'string'")
}
}
}</lang>
}</syntaxhighlight>


Loop through matches
Loop through matches
<lang swift> for x in regex.matchesInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
<syntaxhighlight lang="swift"> for x in regex.matchesInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
let match = x as! NSTextCheckingResult
let match = x as! NSTextCheckingResult
// match.range gives the range of the whole match
// match.range gives the range of the whole match
// match.rangeAtIndex(i) gives the range of the i'th capture group (starting from 1)
// match.rangeAtIndex(i) gives the range of the i'th capture group (starting from 1)
}</lang>
}</syntaxhighlight>


Substitute
Substitute
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let orig = "I am the original string"
let orig = "I am the original string"
Line 2,704: Line 2,704:
let result = regex.stringByReplacingMatchesInString(orig, options: nil, range: NSRange(location: 0, length: count(orig.utf16)), withTemplate: "modified")
let result = regex.stringByReplacingMatchesInString(orig, options: nil, range: NSRange(location: 0, length: count(orig.utf16)), withTemplate: "modified")
println(result)
println(result)
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Test using <code>regexp</code>:
Test using <code>regexp</code>:
<lang tcl>set theString "I am a string"
<syntaxhighlight lang="tcl">set theString "I am a string"
if {[regexp -- {string$} $theString]} {
if {[regexp -- {string$} $theString]} {
puts "Ends with 'string'"
puts "Ends with 'string'"
Line 2,715: Line 2,715:
if {![regexp -- {^You} $theString]} {
if {![regexp -- {^You} $theString]} {
puts "Does not start with 'You'"
puts "Does not start with 'You'"
}</lang>
}</syntaxhighlight>


Extract substring using <code>regexp</code>
Extract substring using <code>regexp</code>
<lang tcl>set theString "This string has >123< a number in it"
<syntaxhighlight lang="tcl">set theString "This string has >123< a number in it"
if {[regexp -- {>(\d+)<} $theString -> number]} {
if {[regexp -- {>(\d+)<} $theString -> number]} {
puts "Contains the number $number"
puts "Contains the number $number"
}</lang>
}</syntaxhighlight>


Substitute using <code>regsub</code>
Substitute using <code>regsub</code>
<lang tcl>set theString = "I am a string"
<syntaxhighlight lang="tcl">set theString = "I am a string"
puts [regsub -- { +a +} $theString { another }]</lang>
puts [regsub -- { +a +} $theString { another }]</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
Line 2,731: Line 2,731:
Toka's regular expression library allows for matching, but does not yet provide for replacing elements within strings.
Toka's regular expression library allows for matching, but does not yet provide for replacing elements within strings.


<lang toka>#! Include the regex library
<syntaxhighlight lang="toka">#! Include the regex library
needs regex
needs regex


Line 2,749: Line 2,749:
#! try-regex will return a flag. -1 is TRUE, 0 is FALSE
#! try-regex will return a flag. -1 is TRUE, 0 is FALSE
expression test.1 2 match try-regex .
expression test.1 2 match try-regex .
expression test.2 2 match try-regex .</lang>
expression test.2 2 match try-regex .</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 2,757: Line 2,757:
Txr is not designed for sed-like filtering, but here is how to do <code>sed -e 's/dog/cat/g'</code>:
Txr is not designed for sed-like filtering, but here is how to do <code>sed -e 's/dog/cat/g'</code>:


<lang txr>@(collect)
<syntaxhighlight lang="txr">@(collect)
@(coll :gap 0)@mismatch@{match /dog/}@(end)@suffix
@(coll :gap 0)@mismatch@{match /dog/}@(end)@suffix
@(output)
@(output)
@(rep)@{mismatch}cat@(end)@suffix
@(rep)@{mismatch}cat@(end)@suffix
@(end)
@(end)
@(end)</lang>
@(end)</syntaxhighlight>


How it works is that the body of the <code>coll</code> uses a double-variable match:
How it works is that the body of the <code>coll</code> uses a double-variable match:
Line 2,782: Line 2,782:
This allows for a very simple, straightforward regex which correctly matches C comments. The <code>freeform</code> operator allows the entire input stream to be treated as one big line, so this works across multi-line comments.
This allows for a very simple, straightforward regex which correctly matches C comments. The <code>freeform</code> operator allows the entire input stream to be treated as one big line, so this works across multi-line comments.


<lang txr>@(freeform)
<syntaxhighlight lang="txr">@(freeform)
@(coll :gap 0)@notcomment@{comment /[/][*].%[*][/]/}@(end)@tail
@(coll :gap 0)@notcomment@{comment /[/][*].%[*][/]/}@(end)@tail
@(output)
@(output)
@(rep)@notcomment @(end)@tail
@(rep)@notcomment @(end)@tail
@(end)</lang>
@(end)</syntaxhighlight>


===Regexes in TXR Lisp===
===Regexes in TXR Lisp===
Line 2,792: Line 2,792:
Parse regex at run time to abstract syntax:
Parse regex at run time to abstract syntax:


<lang sh>$ txr -p '(regex-parse "a.*b")'
<syntaxhighlight lang="sh">$ txr -p '(regex-parse "a.*b")'
(compound #\a (0+ wild) #\b)</lang>
(compound #\a (0+ wild) #\b)</syntaxhighlight>


Dynamically compile regex abstract syntax to regex object:
Dynamically compile regex abstract syntax to regex object:


<lang sh>$ txr -p "(regex-compile '(compound #\a (0+ wild) #\b))"
<syntaxhighlight lang="sh">$ txr -p "(regex-compile '(compound #\a (0+ wild) #\b))"
#<sys:regex: 9c746d0></lang>
#<sys:regex: 9c746d0></syntaxhighlight>


Search replace with <code>regsub</code>.
Search replace with <code>regsub</code>.


<lang sh>$ txr -p '(regsub #/a+/ "-" "baaaaaad")'
<syntaxhighlight lang="sh">$ txr -p '(regsub #/a+/ "-" "baaaaaad")'
"b-d"</lang>
"b-d"</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 2,815: Line 2,815:
{{works with|bash}}
{{works with|bash}}
{{works with|ksh}}
{{works with|ksh}}
<lang bash>s="I am a string"
<syntaxhighlight lang="bash">s="I am a string"
if [[ $s =~ str..g$ ]]; then
if [[ $s =~ str..g$ ]]; then
echo "the string ends with 'str..g'"
echo "the string ends with 'str..g'"
fi</lang>
fi</syntaxhighlight>


===Replacing===
===Replacing===
Given these values
Given these values
<lang bash>s="I am the original string"
<syntaxhighlight lang="bash">s="I am the original string"
re='o.*l'
re='o.*l'
repl="modified"</lang>
repl="modified"</syntaxhighlight>


{{works with|ksh}}
{{works with|ksh}}
Can use regular expressions in parameter expansion
Can use regular expressions in parameter expansion
<lang bash>modified=${s/~(E)$re/$repl}
<syntaxhighlight lang="bash">modified=${s/~(E)$re/$repl}
echo "$modified" # I am the modified string</lang>
echo "$modified" # I am the modified string</syntaxhighlight>


{{works with|bash}}
{{works with|bash}}
have to break apart the original string to build the modified string.
have to break apart the original string to build the modified string.
<lang bash>if [[ $s =~ $re ]]; then
<syntaxhighlight lang="bash">if [[ $s =~ $re ]]; then
submatch=${BASH_REMATCH[0]}
submatch=${BASH_REMATCH[0]}
modified="${s%%$submatch*}$repl${s#*$submatch}"
modified="${s%%$submatch*}$repl${s#*$submatch}"
echo "$modified" # I am the modified string
echo "$modified" # I am the modified string
fi</lang>
fi</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>
<syntaxhighlight lang="vala">
void main(){
void main(){
string sentence = "This is a sample sentence.";
string sentence = "This is a sample sentence.";
Line 2,854: Line 2,854:
stdout.printf("Replaced sentence is: %s\n", sentence);
stdout.printf("Replaced sentence is: %s\n", sentence);
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,864: Line 2,864:
=={{header|VBScript}}==
=={{header|VBScript}}==
Replace white spaces with line breaks.
Replace white spaces with line breaks.
<lang vb>text = "I need more coffee!!!"
<syntaxhighlight lang="vb">text = "I need more coffee!!!"
Set regex = New RegExp
Set regex = New RegExp
regex.Global = True
regex.Global = True
Line 2,872: Line 2,872:
Else
Else
WScript.StdOut.Write "No matching pattern"
WScript.StdOut.Write "No matching pattern"
End If</lang>
End If</syntaxhighlight>
{{in}}
{{in}}
<pre>I need more coffee!!!</pre>
<pre>I need more coffee!!!</pre>
Line 2,887: Line 2,887:


Match text at cursor location:
Match text at cursor location:
<lang vedit>if (Match(".* string$", REGEXP)==0) {
<syntaxhighlight lang="vedit">if (Match(".* string$", REGEXP)==0) {
Statline_Message("This line ends with 'string'")
Statline_Message("This line ends with 'string'")
}</lang>
}</syntaxhighlight>


Search for a pattern:
Search for a pattern:
<lang vedit>if (Search("string$", REGEXP+NOERR)) {
<syntaxhighlight lang="vedit">if (Search("string$", REGEXP+NOERR)) {
Statline_Message("'string' at and of line found")
Statline_Message("'string' at and of line found")
}</lang>
}</syntaxhighlight>


Replace:
Replace:
<lang vedit>Replace(" a ", " another ", REGEXP+NOERR)</lang>
<syntaxhighlight lang="vedit">Replace(" a ", " another ", REGEXP+NOERR)</syntaxhighlight>


=={{header|Web 68}}==
=={{header|Web 68}}==
<lang web68>@1Introduction.
<syntaxhighlight lang="web68">@1Introduction.
Web 68 has access to a regular expression module
Web 68 has access to a regular expression module
which can compile regular expressions,
which can compile regular expressions,
Line 2,957: Line 2,957:
ca -l mod rosettacoderegex.w68
ca -l mod rosettacoderegex.w68
That's it. The resulting binary will print
That's it. The resulting binary will print
'String "string$" matches string "This is a string"'</lang>
'String "string$" matches string "This is a string"'</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,963: Line 2,963:
{{libheader|Wren-pattern}}
{{libheader|Wren-pattern}}
The above module allows us to do simple string pattern matching and replacement in a similar fashion to regular expressions but using a different syntax. SenseTalk's examples have been borrowed for this purpose.
The above module allows us to do simple string pattern matching and replacement in a similar fashion to regular expressions but using a different syntax. SenseTalk's examples have been borrowed for this purpose.
<lang ecmascript>import "/pattern" for Pattern
<syntaxhighlight lang="ecmascript">import "/pattern" for Pattern


var s = "This is a story about R2D2 and C3P0 who are best friends."
var s = "This is a story about R2D2 and C3P0 who are best friends."
Line 2,987: Line 2,987:
var t = m.capsText
var t = m.capsText
System.print(" %(t[1]), %(t[0]) - %(t[2])")
System.print(" %(t[1]), %(t[0]) - %(t[2])")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,010: Line 3,010:
{{libheader|Wren-regex}}
{{libheader|Wren-regex}}
The above module uses RE2 regular expression syntax but, since it is a wrapper for Go's 'regexp' package, it can only be used from a special embedded application and not by Wren-cli.
The above module uses RE2 regular expression syntax but, since it is a wrapper for Go's 'regexp' package, it can only be used from a special embedded application and not by Wren-cli.
<lang ecmascript>/* regular_expressions.wren */
<syntaxhighlight lang="ecmascript">/* regular_expressions.wren */
import "./regex" for Regex
import "./regex" for Regex


Line 3,040: Line 3,040:
var m = re2.findSubmatch(record)
var m = re2.findSubmatch(record)
System.print(" %(m[2]), %(m[1]) - %(m[3])")
System.print(" %(m[2]), %(m[1]) - %(m[3])")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,050: Line 3,050:
The build in RE engine is a basic one.<br/>
The build in RE engine is a basic one.<br/>
Strings are immutable so replacement is creation.
Strings are immutable so replacement is creation.
<lang zkl>var re=RegExp(".*string$");
<syntaxhighlight lang="zkl">var re=RegExp(".*string$");
re.matches("I am a string") //-->True
re.matches("I am a string") //-->True
var s="I am a string thing"
var s="I am a string thing"
Line 3,060: Line 3,060:
re.search(s,True); // using .matched clears it
re.search(s,True); // using .matched clears it
m:=re.matched[1];
m:=re.matched[1];
s.replace(m,"FOO"); // -->"I am a FOO thing"</lang>
s.replace(m,"FOO"); // -->"I am a FOO thing"</syntaxhighlight>


Using a mutable byte bucket:
Using a mutable byte bucket:
<lang zkl>var s=Data(0,Int,"I am a string thing");
<syntaxhighlight lang="zkl">var s=Data(0,Int,"I am a string thing");
re.search(s,True);
re.search(s,True);
p,n:=re.matched[0];
p,n:=re.matched[0];
s[p,n]="FOO";
s[p,n]="FOO";
s.text //-->"I am a FOO thing"</lang>
s.text //-->"I am a FOO thing"</syntaxhighlight>