View Problem

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ExpandDiskEdit
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
DiskEdit
csharp
using System;
using System.Text.RegularExpressions;

public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";

Match match = Regex.Match(oneTwoThree, pattern);

// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
DiskEdit
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
DiskEdit
groovy
matcher = ("one two three" =~ /one (.*) three/)
if (matcher) println matcher[0][1]
DiskEdit
groovy 1.6.1+
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match

Submit a new solution for java, csharp, clojure, or groovy
There are 14 other solutions in additional languages (cpp, erlang, fantom, fsharp ...)