Anonymous user
Regular expressions: Difference between revisions
m
Fixed lang tags.
(Added Scala) |
m (Fixed lang tags.) |
||
Line 7:
=={{header|AppleScript}}==
{{libheader|Satimage.osax}}
<lang applescript>try
=={{header|ALGOL 68}}==
Line 24:
<!-- {{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}}
<lang
STRING str := "i am a string";
Line 51:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
For example:<lang
FILE file; STRING book; associate(file, book);
on value error(file, (REF FILE f)BOOL: stop);
Line 71 ⟶ 70:
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % foundpos := RegExMatch("Hello World", "World$")
MsgBox %
=={{header|AWK}}==
AWK supports regular expressions, which are typically marked up with slashes in front and back, and the "~" operator:
As shorthand, a regular expression in the condition part fires if it matches an input line:
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):
This variant matches one or more uppercase letters in one round:
=={{header|C}}==
Line 152 ⟶ 149:
{{libheader|Boost}}
<lang cpp>
{
boost::regex re(".* string$");
std::string s = "Hi, I am a string";
// match the complete string
if (boost::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
// match a substring
boost::regex re2(" a.*a");
boost::smatch match;
if (boost::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
}
// replace a substring
std::string dest_string;
boost::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
}</lang>
=={{header|C sharp|C#}}==
Line 235 ⟶ 232:
=={{header|D}}==
<lang d>
Note that in std.string there are string functions to perform those string operations in a faster way.
=={{header|Erlang}}==
<lang erlang>match() ->
String = "This is a string",
case re:run(String, "string$") of
Line 271 ⟶ 267:
String = "This is a string",
NewString = re:replace(String, " a ", " another ", [{return, list}]),
io:format("~s~n",[NewString]).</lang>
=={{header|Forth}}==
{{libheader|Forth Foundation Library}}
Test/Match
=={{header|Haskell}}==
Test
<lang haskell>
Substitute
<lang haskell>
=={{header|J}}==
Line 318 ⟶ 313:
J's regex support is built on top of PCRE.
<lang
Matching:
<lang j> '.*string$' rxeq str NB. 1 is true, 0 is false
1</lang>
Substitution:
<lang j> ('am';'am still') rxrplc str
=={{header|Java}}==
Line 335 ⟶ 330:
Test
<lang java>
Substitute
<lang java>
=={{header|JavaScript}}==
Test/Match
<lang javascript>
Substitute
<lang javascript>
=={{header|M4}}==
<lang M4>regexp(`GNUs not Unix', `\<[a-z]\w+')
regexp(`GNUs not Unix', `\<[a-z]\(\w+\)', `a \& b \1 c')</lang>
Output:
Line 386 ⟶ 379:
Test
{{works with|Mac OS X|10.4+}}
<lang objc>NSString *str = @"I am a string";
NSString *regex = @".*string$";
Line 394 ⟶ 386:
if ([pred evaluateWithObject:str]) {
NSLog(@"ends with 'string'");
}</lang>
Unfortunately this method cannot find the location of the match or do substitution.
Line 401 ⟶ 392:
=== With the standard library ===
Test
<lang ocaml>
Substitute
<lang ocaml>
=== Using Pcre ===
Line 467 ⟶ 458:
Test
<lang php>
Replace
<lang php>
=={{header|PowerShell}}==
Line 495 ⟶ 486:
=={{header|R}}==
First, define some strings.
<lang R>pattern <- "string"
text1 <- "this is a matching string"
text2 <- "this does not match"</lang>
Matching with grep. The indices of the texts containing matches are returned.
<lang R>grep(pattern, c(text1, text2)) # 1</lang>
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>
[1] 20 -1
attr(,"match.length")
[1] 6 -1
Replacement
<lang R>gsub(pattern, "pair of socks", c(text1, text2))</lang>
[1] "this is a matching pair of socks" "this does not match"
=={{header|Raven}}==
Match:
Replace:
=={{header|Ruby}}==
Test
<lang ruby>
Substitute
<lang ruby>
Substitute using block
<lang ruby>
=={{header|Scala}}==
Line 554 ⟶ 537:
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 Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups</lang>
Search and replace with string methods:
<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" replaceAll ("b", "B") // Multiple replacement</lang>
Search with regex methods:
Line 569 ⟶ 550:
Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None
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>
Using pattern matching with regex:
Line 585 ⟶ 565:
for {
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>
Replacing with regex:
<lang scala>Bottles2 replaceFirstIn ("99 bottles of beer", "98 bottles of beer")
Bottles3 replaceAllIn ("99 bottles of beer", "98 bottles of beer")</lang>
=={{header|Slate}}==
Line 597 ⟶ 575:
This library is still in its early stages. There isn't currently a feature to replace a substring.
<lang slate>(Regex Matcher newOn: '^(([^:/?#]+)\\:)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?')
`>> [match: 'http://slatelanguage.org/test/page?query'. subexpressionMatches]
"==> {"Dictionary traitsWindow" 0 -> 'http:'. 1 -> 'http'. 2 -> '//slatelanguage.org'.
3 -> 'slatelanguage.org'. 4 -> '/test/page'. 5 -> '?query'. 6 -> 'query'. 7 -> Nil}"</lang>
=={{header|Smalltalk}}==
Line 652 ⟶ 627:
Toka's regular expression library allows for matching, but does not yet provide for replacing elements within strings.
=={{header|Vedit macro language}}==
Line 676 ⟶ 651:
Match text at cursor location:
<lang vedit>if (Match(".* string$", REGEXP)==0) {
Statline_Message("This line ends with 'string'")
}</lang>
Search for a pattern:
<lang vedit>if (Search("string$", REGEXP+NOERR)) {
Statline_Message("'string' at and of line found")
}</lang>
Replace:
<lang vedit>Replace(" a ", " another ", REGEXP+NOERR)</lang>
|