View Problem

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
DiskEdit
ruby
puts $1 if "one two three"=~/^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
perl
print $1 if "one two three"=~/^one (.*) three$/
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
ExpandDiskEdit
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))
DiskEdit
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)
ExpandDiskEdit
cpp C++/CLI .NET 2.0
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
ExpandDiskEdit
cpp
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;
ExpandDiskEdit
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
DiskEdit
erlang 12B3+
case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end.
DiskEdit
ocaml
#load "str.cma" ;;

let s = "one two three" in
if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then
print_string (Str.matched_group 1 s)
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]);
}
}
ExpandDiskEdit
php
preg_match('/one (.*) three/', 'one two three', $matches);
echo $matches[1];
ExpandDiskEdit
php
ereg('one (.*) three', 'one two three', $regs);
echo $regs[1];
DiskEdit
haskell
import Text.Regex
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
DiskEdit
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
ExpandDiskEdit
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")
ExpandDiskEdit
go
re, _ := regexp.Compile("one (.*) three")
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}

Submit a new solution for ruby, java, perl, groovy ...