Regular expressions: Difference between revisions

→‎{{header|Wren}}: Added a second version using Wren-regex module.
m (→‎{{header|Phix}}: syntax coloured, made p2js compatible, regex.e needed a couple of bugfixes)
(→‎{{header|Wren}}: Added a second version using Wren-regex module.)
Line 2,960:
 
=={{header|Wren}}==
===Version 1 (Wren-pattern)===
{{libheader|Wren-pattern}}
Wren doesn't have regular expressions as such but theThe 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
 
Line 3,004 ⟶ 3,005:
Granger, Hermione - 59867125
Weasley, Ron - 56471832
</pre>
<br>
===Version 2 (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.
<lang ecmascript>/* regular_expressions.wren */
import "./regex" for Regex
 
var s = "This is a story about R2D2 and C3P0 who are best friends."
var re = Regex.compile("""[A-Z]\d[A-Z]\d""")
var matches = re.findAll(s)
var indices = re.findAllIndex(s)
System.print("Original string:\n%(" %(s)")")
 
System.print("\nThe following matches were found:")
for (i in 0...matches.count) {
var m = matches[i]
var ix = indices[i][0]
System.print(" %(m) at index %(ix)")
}
 
System.print("\nAfter replacing the second match:")
System.print(" %(re.replaceAll(s, "Luke", 2, 1))") // replace 2nd match with "Luke"
 
System.print("\nReformatted phone list example:")
var phoneList = [
"Harry Potter 98951212",
"Hermione Granger 59867125",
"Ron Weasley 56471832"
]
 
var re2 = Regex.compile("""([A-Za-z]+) ([A-Za-z]+) (\d{8})""")
for (record in phoneList) {
var m = re2.findSubmatch(record)
System.print(" %(m[2]), %(m[1]) - %(m[3])")
}</lang>
 
{{out}}
<pre>
Identical to first version.
</pre>
 
9,476

edits