Regular expressions: Difference between revisions

(Omitted EasyLang)
 
(3 intermediate revisions by 3 users not shown)
Line 1,246:
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">
/* match entire string against a pattern */
boolean isNumber = "-1234.567".matches("-?\\d+(?:\\.\\d+)?");
 
/* substitute part of string using a pattern */
String reduceSpaces = "a b c d e f".replaceAll(" +", " ");
</syntaxhighlight>
<syntaxhighlight lang="java">
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
/* group capturing example */
Pattern pattern = Pattern.compile("(?:(https?)://)?([^/]+)/(?:([^#]+)(?:#(.+))?)?");
Matcher matcher = pattern.matcher("https://rosettacode.org/wiki/Regular_expressions#Java");
if (matcher.find()) {
String protocol = matcher.group(1);
String authority = matcher.group(2);
String path = matcher.group(3);
String fragment = matcher.group(4);
}
</syntaxhighlight>
<syntaxhighlight lang="java">
/* split a string using a pattern */
String[] strings = "abc\r\ndef\r\nghi".split("\r\n?");
</syntaxhighlight>
 
<br />
An alternate demonstration
{{works with|Java|1.4+}}
Test
Line 1,359 ⟶ 1,388:
 
=={{header|langur}}==
Langur uses semi-integreted regex. The following examples use re2 regex literals.
 
There are several functions that can be used with regexes, such as match(), replace(), split(), etc. They can also be matched inusing athe givenforward expressionoperator test(->).
 
To match a string, ...
<syntaxhighlight lang="langur">if matching("somestring" -> re/abc/, "somestring") { ... }</syntaxhighlight>
 
Or...
{{works with|langur|0.10}}
<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.
<syntaxhighlight lang="langur">if val (.x, .y) = submatch(re/(abc+).+?(def)/, "somestring") { ... }</syntaxhighlight>
 
Or...
<syntaxhighlight lang="langur">givenswitch "somestring" {
case -> re/abc/: ...
...
}</syntaxhighlight>
 
Or...
<syntaxhighlight lang="langur">givenswitch -> re/abc/ {
case "somestring": ...
...
Line 2,964 ⟶ 2,989:
{{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.
<syntaxhighlight lang="ecmascriptwren">import "./pattern" for Pattern
 
var s = "This is a story about R2D2 and C3P0 who are best friends."
Line 3,011 ⟶ 3,036:
{{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.
<syntaxhighlight lang="ecmascriptwren">/* regular_expressionsRegular_expressions_2.wren */
import "./regex" for Regex
 
885

edits