Text between: Difference between revisions

m
(Add Rust implementation)
m (→‎{{header|Wren}}: Minor tidy)
 
(38 intermediate revisions by 25 users not shown)
Line 1:
{{draft task|Text between}}
[[Category:Strings]]
 
;Task:
Line 14 ⟶ 15:
 
Example 1. Both delimiters set
 
<pre>
Text: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: " world"
Output: "Rosetta Code"
</pre>
 
Example 2. Start delimiter is the start of the string
 
<pre>
Text: "Hello Rosetta Code world"
Start delimiter: "start"
End delimiter: " world"
Output: "Hello Rosetta Code"
</pre>
 
Example 3. End delimiter is the end of the string
 
<pre>
Text: "Hello Rosetta Code world"
Start delimiter: "Hello"
End delimiter: "end"
Output: "Rosetta Code world"
</pre>
 
Example 4. End delimiter appears before and after start delimiter
 
<pre>
Text: "</div><div style=\"chinese\">你好嗎</div>"
Start delimiter: "<div style=\"chinese\">"
End delimiter: "</div>"
Output: "你好嗎"
</pre>
 
Example 5. End delimiter not present
 
<pre>
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
Start delimiter: "<text>"
End delimiter: "<table>"
Output: "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
</pre>
 
Example 6. Start delimiter not present
 
<pre>
Text: "<table style=\"myTable\"><tr><td>hello world</td></tr></table>"
Start delimiter: "<table>"
End delimiter: "</table>"
Output: ""
</pre>
 
Example 7. Multiple instances of end delimiter after start delimiter (match until the first one)
 
<pre>
Text: "The quick brown fox jumps over the lazy other fox"
Start delimiter: "quick "
End delimiter: " fox"
Output: "brown"
</pre>
 
Example 8. Multiple instances of the start delimiter (start matching at the first one)
 
<pre>
Text: "One fish two fish red fish blue fish"
Start delimiter: "fish "
End delimiter: " red"
Output: "two fish"
</pre>
 
Example 9. Start delimiter is end delimiter
<pre>
Text: "FooBarBazFooBuxQuux"
Start delimiter: "Foo"
End delimiter: "Foo"
Output: "BarBaz"
</pre>
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F textBetween(thisText, startString, endString)
X.try
Int startIndex
I startString == ‘start’
startIndex = 0
E
startIndex = thisText.index(startString)
 
I !(startIndex >= 0)
R ‘Start delimiter not found’
E
I startString != ‘start’
startIndex = startIndex + startString.len
 
V returnText = thisText[startIndex ..]
 
I endString == ‘end’
R returnText
E
V endIndex = returnText.index(endString)
 
I !(endIndex >= 0)
R ‘End delimiter not found’
E
returnText = returnText[0 .< endIndex]
 
R returnText
 
X.catch ValueError
R ‘Value error’
 
:start:
V thisText = :argv[1]
V startString = :argv[2]
V endString = :argv[3]
print(textBetween(thisText, startString, endString))</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC Matches(CHAR ARRAY text,sub BYTE index)
CHAR ARRAY tmp(255)
 
SCopyS(tmp,text,index,index+sub(0)-1)
IF SCompare(tmp,sub)=0 THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC FindFrom(CHAR ARRAY text,delim BYTE start)
BYTE i,end
 
IF text(0)<delim(0) OR delim(0)=0 THEN
RETURN (0)
FI
end=text(0)-delim(0)+1
FOR i=start TO end
DO
IF Matches(text,delim,i) THEN
RETURN (i)
FI
OD
RETURN (0)
 
PROC TextBetween(CHAR ARRAY text,start,end,res)
BYTE first,last
 
IF SCompare(start,"start")=0 THEN
first=1
ELSE
first=FindFrom(text,start,1)
IF first=0 THEN
res(0)=0
RETURN
ELSE
first==+start(0)
FI
FI
 
IF SCompare(end,"end")=0 THEN
last=text(0)
ELSE
last=FindFrom(text,end,first+1)
IF last<=first THEN
last=text(0)
ELSE
last==-1
FI
FI
 
SCopyS(res,text,first,last)
RETURN
 
PROC Test(BYTE n CHAR ARRAY text,start,end)
CHAR ARRAY res(255)
 
TextBetween(text,start,end,res)
PrintF("Ex%B. ""%S""%E%E",n,res)
RETURN
 
PROC Main()
Test(1,"Hello Rosetta Code world","Hello "," world")
Test(2,"Hello Rosetta Code world","start"," world")
Test(3,"Hello Rosetta Code world","Hello ","end")
Test(4,"</div><div style=\""chinese\"">???</div>","<div style=\""chinese\"">","</div>")
Test(5,"<text>Hello <span>Rosetta Code</span> world</text><table style=\""myTable\"">","<text>","<table>")
Test(6,"<table style=\""myTable\""><tr><td>hello world</td></tr></table>","<table>","</table>")
Test(7,"The quick brown fox jumps over the lazy other fox","quick "," fox")
Test(8,"One fish two fish red fish blue fish","fish "," red")
Test(9,"FooBarBazFooBuxQuux","Foo","Foo")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Text_between.png Screenshot from Atari 8-bit computer]
<pre>
Ex1. "Rosetta Code"
Text: "FooBarBazFooBuxQuux"
 
Start delimiter: "Foo"
Ex2. "Hello Rosetta Code"
End delimiter: "Foo"
 
Output: "BarBaz"
Ex3. "Rosetta Code world"
 
Ex4. "???"
 
Ex5. "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
 
Ex6. ""
 
Ex7. "brown"
 
Ex8. "two fish"
 
Ex9. "BarBaz"
</pre>
 
=={{header|Ada}}==
<br>
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Strings.Fixed;
 
procedure Text_Between is
 
Default_Start : constant String := "start";
Default_End : constant String := "end";
 
function Between (Item : String;
First : String := Default_Start;
Last : String := Default_End) return String
is
use Ada.Strings.Fixed;
First_Pos : Natural;
Last_Pos : Natural;
begin
if First = Default_Start then
First_Pos := Item'First;
else
First_Pos := Index (Item, First);
if First_Pos = 0 then
return "";
else
First_Pos := First_Pos + First'Length;
end if;
end if;
 
if Last = Default_End then
return Item (First_Pos .. Item'Last);
else
Last_Pos := Index (Item (First_Pos .. Item'Last), Last);
if Last_Pos = 0 then
return Item (First_Pos .. Item'Last);
else
return Item (First_Pos .. Last_Pos - 1);
end if;
end if;
end Between;
 
procedure Test_Between (Text, First, Last : String) is
use Ada.Text_Io;
function Quote (Item : String) return String is ("'" & Item & "'");
Result : String renames Between (Text, First, Last);
begin
Put ("Text: "); Put_Line (Quote (Text));
Put ("Start: "); Put_Line (Quote (First));
Put ("End: "); Put_Line (Quote (Last));
Put ("Result: "); Put_Line (Quote (Result));
New_Line;
end Test_Between;
 
begin
Test_Between ("Hello Rosetta Code world", First => "Hello ", Last => " world");
Test_Between ("Hello Rosetta Code world", First => Default_Start, Last => " world");
Test_Between ("Hello Rosetta Code world", First => "Hello ", Last => Default_End);
Test_Between ("</div><div style=\""chinese\"">你好嗎</div>",
First => "<div style=\""chinese\"">", Last => "</div>");
Test_Between ("<text>Hello <span>Rosetta Code</span> world</text><table style=\""myTable\"">",
First => "<text>", Last => "<table>");
Test_Between ("<table style=\""myTable\""><tr><td>hello world</td></tr></table>",
First => "<table>", Last => "</table>");
Test_Between ("The quick brown fox jumps over the lazy other fox",
First => "quick ", Last => " fox");
Test_Between ("One fish two fish red fish blue fish", First => "fish ", Last => " red");
Test_Between ("FooBarBazFooBuxQuux", First => "Foo", Last => "Foo");
end Text_Between;</syntaxhighlight>
{{out}}
<pre>
Text: 'Hello Rosetta Code world'
Start: 'Hello '
End: ' world'
Result: 'Rosetta Code'
 
Text: 'Hello Rosetta Code world'
Start: 'start'
End: ' world'
Result: 'Hello Rosetta Code'
 
Text: 'Hello Rosetta Code world'
Start: 'Hello '
End: 'end'
Result: 'Rosetta Code world'
 
Text: '</div><div style=\"chinese\">你好嗎</div>'
Start: '<div style=\"chinese\">'
End: '</div>'
Result: '你好嗎'
 
Text: '<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">'
Start: '<text>'
End: '<table>'
Result: 'Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">'
 
Text: '<table style=\"myTable\"><tr><td>hello world</td></tr></table>'
Start: '<table>'
End: '</table>'
Result: ''
 
Text: 'The quick brown fox jumps over the lazy other fox'
Start: 'quick '
End: ' fox'
Result: 'brown'
 
Text: 'One fish two fish red fish blue fish'
Start: 'fish '
End: ' red'
Result: 'two fish'
 
Text: 'FooBarBazFooBuxQuux'
Start: 'Foo'
End: 'Foo'
Result: 'BarBaz'
</pre>
 
=={{header|ALGOL 68}}==
Line 100 ⟶ 342:
Uses the Algol 68G specific string in string, for other compilers/interpreters, a version of string in string is here : [[ALGOL_68/prelude]].<br/>
As Algol 68 predates Unicode, the fourth example deviates from the task.
<langsyntaxhighlight lang="algol68">BEGIN
# some utility operators #
# returns the length of a string #
Line 170 ⟶ 412:
trace between := FALSE
END
END</langsyntaxhighlight>
{{out}}
<pre>
Line 221 ⟶ 463:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">
my text_between("Hello Rosetta Code world", "Hello ", " world")
 
Line 243 ⟶ 485:
return return_text
end text_between
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">data =
(
Hello Rosetta Code world|Hello | world|
Hello Rosetta Code world|start| world|
Hello Rosetta Code world|Hello |end|
</div><div style=\"chinese\">你好嗎</div>|<div style=\"chinese\">|</div>|
<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">|<text>|<table>|
<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">|<table>|</table>|
The quick brown fox jumps over the lazy other fox|quick | fox|
One fish two fish red fish blue fish|fish | red|
FooBarBazFooBuxQuux|Foo|Foo|
)
result := ""
for i, line in StrSplit(data, "`n", "`r")
x := StrSplit(line, "|")
, result .= "text: """ x.1 """`nstart: """ x.2 """`tend: """ x.3 """`noutput: """ textBetween(x.1, x.2, x.3) """`n----`n"
MsgBox, 262144, , % result
return
 
textBetween(text, start, end){
RegExMatch(text,(start="start"?"^":"\Q" start "\E") "(.*?)" (end="end"?"$":"\Q" end "\E?"),m)
return m1
}</syntaxhighlight>
{{out}}
<pre>text: "Hello Rosetta Code world"
start: "Hello " end: " world"
output: "Rosetta Code"
----
text: "Hello Rosetta Code world"
start: "start" end: " world"
output: "Hello Rosetta Code"
----
text: "Hello Rosetta Code world"
start: "Hello " end: "end"
output: "Rosetta Code world"
----
text: "</div><div style=\"chinese\">你好嗎</div>"
start: "<div style=\"chinese\">" end: "</div>"
output: "你好嗎"
----
text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
start: "<text>" end: "<table>"
output: "Hello <span>Rosetta Code</span> world</text>"
----
text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
start: "<table>" end: "</table>"
output: ""
----
text: "The quick brown fox jumps over the lazy other fox"
start: "quick " end: " fox"
output: "brown"
----
text: "One fish two fish red fish blue fish"
start: "fish " end: " red"
output: "two fish"
----
text: "FooBarBazFooBuxQuux"
start: "Foo" end: "Foo"
output: "BarBaz"
----</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TEXT_BETWEEN.AWK
BEGIN {
Line 295 ⟶ 600:
printf("Output: '%s'\n\n",str)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 372 ⟶ 677:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang c>
/*
* textBetween: Gets text between two delimiters
Line 431 ⟶ 736:
return startPointer;
} // end textBetween method</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{trans|D}}
<syntaxhighlight lang="csharp">using System;
 
namespace TextBetween {
class Program {
static string TextBetween(string source, string beg, string end) {
int startIndex;
 
if (beg == "start") {
startIndex = 0;
}
else {
startIndex = source.IndexOf(beg);
if (startIndex < 0) {
return "";
}
startIndex += beg.Length;
}
 
int endIndex = source.IndexOf(end, startIndex);
if (endIndex < 0 || end == "end") {
return source.Substring(startIndex);
}
return source.Substring(startIndex, endIndex - startIndex);
}
 
static void Print(string s, string b, string e) {
Console.WriteLine("text: '{0}'", s);
Console.WriteLine("start: '{0}'", b);
Console.WriteLine("end: '{0}'", e);
Console.WriteLine("result: '{0}'", TextBetween(s, b, e));
Console.WriteLine();
}
 
static void Main(string[] args) {
Print("Hello Rosetta Code world", "Hello ", " world");
Print("Hello Rosetta Code world", "start", " world");
Print("Hello Rosetta Code world", "Hello ", "end");
Print("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>");
Print("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>");
Print("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>");
Print("The quick brown fox jumps over the lazy other fox", "quick ", " fox");
Print("One fish two fish red fish blue fish", "fish ", " red");
Print("FooBarBazFooBuxQuux", "Foo", "Foo");
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <iostream>
 
std::ostream& operator<<(std::ostream& out, const std::string& str) {
Line 481 ⟶ 835:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>text: 'Hello Rosetta Code world'
Line 522 ⟶ 876:
end: 'Foo'
result: 'BarBaz'</pre>
 
=={{header|C#|C sharp}}==
{{trans|D}}
<lang csharp>using System;
 
namespace TextBetween {
class Program {
static string TextBetween(string source, string beg, string end) {
int startIndex;
 
if (beg == "start") {
startIndex = 0;
}
else {
startIndex = source.IndexOf(beg);
if (startIndex < 0) {
return "";
}
startIndex += beg.Length;
}
 
int endIndex = source.IndexOf(end, startIndex);
if (endIndex < 0 || end == "end") {
return source.Substring(startIndex);
}
return source.Substring(startIndex, endIndex - startIndex);
}
 
static void Print(string s, string b, string e) {
Console.WriteLine("text: '{0}'", s);
Console.WriteLine("start: '{0}'", b);
Console.WriteLine("end: '{0}'", e);
Console.WriteLine("result: '{0}'", TextBetween(s, b, e));
Console.WriteLine();
}
 
static void Main(string[] args) {
Print("Hello Rosetta Code world", "Hello ", " world");
Print("Hello Rosetta Code world", "start", " world");
Print("Hello Rosetta Code world", "Hello ", "end");
Print("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>");
Print("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>");
Print("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>");
Print("The quick brown fox jumps over the lazy other fox", "quick ", " fox");
Print("One fish two fish red fish blue fish", "fish ", " red");
Print("FooBarBazFooBuxQuux", "Foo", "Foo");
}
}
}</lang>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.algorithm.searching;
import std.stdio;
import std.string;
Line 616 ⟶ 921:
print("One fish two fish red fish blue fish", "fish ", " red");
print("FooBarBazFooBuxQuux", "Foo", "Foo");
}</langsyntaxhighlight>
{{out}}
<pre>text: 'Hello Rosetta Code world'
Line 662 ⟶ 967:
end: 'Foo'
result: 'BarBaz'</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Text_between;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
function TextBetween(source, bg, ed: string): string;
var
startIndex, edIndex: Integer;
begin
if bg = 'start' then
startIndex := 0
else
begin
startIndex := source.IndexOf(bg);
if startIndex < 0 then
Exit('');
 
startIndex := startIndex + bg.Length;
end;
edIndex := source.IndexOf(ed, startIndex);
 
if (edIndex < 0) or (ed = 'end') then
Exit(source.Substring(startIndex));
Exit(source.Substring(startIndex, edIndex - startIndex));
end;
 
procedure Print(s, b, e: string; var ExempleIndex: Integer);
begin
Writeln('Exemple ', ExempleIndex, ':');
Writeln(Format('Text: "%s"', [s]));
Writeln(Format('Start: "%s"', [b]));
Writeln(Format('End: "%s"', [e]));
Writeln(Format('Result: "%s"'#10, [TextBetween(s, b, e)]));
inc(ExempleIndex);
end;
 
var
ExempleIndex: Integer = 1;
 
begin
Print('Hello Rosetta Code world', 'Hello ', ' world', ExempleIndex);
 
Print('Hello Rosetta Code world', 'start', ' world', ExempleIndex);
 
Print('Hello Rosetta Code world', 'Hello ', 'end', ExempleIndex);
 
Print('</div><div style=\"chinese\">你好嗎</div>', '<div style=\"chinese\">',
'</div>', ExempleIndex);
 
Print('<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">',
'<text>', '<table>', ExempleIndex);
 
Print('<table style=\"myTable\"><tr><td>hello world</td></tr></table>',
'<table>', '</table>', ExempleIndex);
 
Print('The quick brown fox jumps over the lazy other fox', 'quick ', ' fox',
ExempleIndex);
 
Print('One fish two fish red fish blue fish', 'fish ', ' red', ExempleIndex);
 
Print('FooBarBazFooBuxQuux', 'Foo', 'Foo', ExempleIndex);
 
Readln;
end.</syntaxhighlight>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators formatting kernel locals math
prettyprint.config sequences ;
IN: rosetta-code.text-between
Line 706 ⟶ 1,080:
] each ;
 
MAIN: text-between-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 754 ⟶ 1,128:
Output: "BarBaz"
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|VBA}}
<syntaxhighlight lang="freebasic">Const DELIM_INICIO As String = "start"
Const DELIM_FINAL As String = "end"
 
Function Text_Between(T As String, F As String, L As String) As String
Dim As Long i = Instr(T, L) + 1
If T = "" Or F = "" Or (Instr(T, F) = 0 And F <> DELIM_INICIO) Then
Return ""
Elseif F = DELIM_INICIO And L = DELIM_FINAL Then
Return T
Elseif F = DELIM_INICIO Then
Return Mid(T, 1, Instr(T, L) - 1)
Elseif L = DELIM_FINAL Or Instr(T, L) = 0 Or (Instr(T, L) < Instr(T, F) And Instr(i, T, L) = 0) Then
Return Mid(T, Len(F) + Instr(T, F))
Elseif F = L Then
Return Mid(T, Len(F) + Instr(T, F) Or Instr(i, T, F) - Len(F) - 1)
Else
Return Mid(T, Len(F) + Instr(T, F), Instr(Instr(T, F), T, L) - (Len(F) + Instr(T, F)))
End If
End Function
 
Dim Texto As String, Inicio As String, Final As String, Salida As String
'Ejemplo 1. Both delimiters set
Texto = "Hello Rosetta Code world"
Inicio = "Hello "
Final = " world"
Salida = "1- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 2. start delimiter is the start of the string
Texto = "Hello Rosetta Code world"
Inicio = "start"
Final = " world"
Salida += "2- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 3. end delimiter is the end of the string
Texto = "Hello Rosetta Code world"
Inicio = "Hello "
Final = "end"
Salida += "3- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 4. end delimiter appears before and after start delimiter
Texto = "</div><div style=\""chinese\"">???</div>..."
Inicio = "<div style=\""chinese\"">"
Final = "</div>"
Salida += "4- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 5. end delimiter not present
Texto = "<Texto>Hello <span>Rosetta Code</span> world</Texto><table style=\""myTable\"">"
Inicio = "<Texto>"
Final = "<table>"
Salida += "5- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 6. start delimiter not present
Texto = "<table style=\""myTable\""><tr><td>hello world</td></tr></table>"
Inicio = "<table>"
Final = "</table>"
Salida += "6- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 7. Multiple instances of end delimiter after start delimiter (match until the Inicio one)
Texto = "The quick brown fox jumps over the lazy other fox"
Inicio = "quick "
Final = " fox"
Salida += "7- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 8. Multiple instances of the start delimiter (start matching at the Inicio one)
Texto = "One fish two fish red fish blue fish"
Inicio = "fish "
Final = " red"
Salida += "8- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 9. start delimiter is end delimiter
Texto = "FooBarBazFooBuxQuux"
Inicio = "Foo"
Final = "Foo"
Salida += "9- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 10 : end delimiter appears before and NOT after start delimiter
Texto = "</div><div style=\""chinese\"">???..."
Inicio = "<div style=\""chinese\"">"
Final = "</div>"
Salida += "10- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 11. Texto = ""
Texto = ""
Inicio = "start"
Final = "end"
Salida += "11- " + Text_Between(Texto, Inicio, Final) + Chr(10)
'Ejemplo 12. start and end delimiters use special values
Texto = "Hello Rosetta Code world"
Inicio = "start"
Final = "end"
Salida += "12- " + Text_Between(Texto, Inicio, Final)
'Resultado:
Print Salida
Sleep</syntaxhighlight>
{{out}}
<pre>
1- Rosetta Code
2- Hello Rosetta Code
3- Rosetta Code world
4- ???
5- Hello <span>Rosetta Code</span> world</Texto><table style=\"myTable\">
6-
7- brown
8- two fish
9- rBazFooBuxQuux
10- ???...
11-
12- Hello Rosetta Code world
</pre>
 
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 817 ⟶ 1,295:
fmt.Printf("Output: \"%s\"\n\n", b)
}
}</langsyntaxhighlight>
 
{{out}}
Line 825 ⟶ 1,303:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Control.Monad (join)
<lang Haskell>import Data.Text (Text, pack, unpack, breakOn, stripPrefix)
import Data.Bifunctor (bimap)
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import Data.Text (Text, breakOn, pack, stripPrefix, unpack)
import Control.Arrow ((***))
 
----------------------- TEXT BETWEEN ---------------------
 
textBetween ::
-- TEXT BETWEEN -----------------------------------------------------------
textBetween :: (Either String Text, Either String Text) -> Text -> Text
Text ->
Text
textBetween (start, end) txt =
fromMaybe
let retain sub part delim t =
(pack [])
either (Just . const t) (sub $ part . flip breakOn t) delim
( retain (stripPrefix <*>) snd start txt
in fromMaybe
>>= retain (packJust [].) fst end
)
(retain (stripPrefix <*>) snd start txt >>= retain (Just .) fst end)
where
retain sub part delim t =
either
(Just . const t)
(sub $ part . flip breakOn t)
delim
 
-------------------------- TESTS -------------------------
main :: IO ()
main = do
mapM_ print $
flip textBetween (head samples)
<$> take 3 delims
(putStrLn . unlines) $
zipWith
( \d t ->
intercalate
(unpack $ textBetween d t)
["\"", "\""]
)
(drop 3 delims)
(tail samples)
 
-- TESTS ------------------------------------------------------------------
samples :: [Text]
samples =
fmap
pack <$>
pack
[ "Hello Rosetta Code world"
[ "Hello Rosetta Code world",
, "</div><div style=\"chinese\">你好吗</div>"
, "<text>Hello <span>Rosetta Code</span> world"</textdiv><tablediv style=\"myTablechinese\">你好吗</div>",
"<text>Hello <span>Rosetta Code</span> world"
, "<table style=\"myTable\"><tr><td>hello world</td></tr></table>"
<> "</text><table style=\"myTable\">",
]
"<table style=\"myTable\"><tr><td>"
<> "hello world</td></tr></table>"
]
 
delims :: [(Either String Text, Either String Text)]
delims =
fmap
(wrap *** wrap) <$>
[ ("Hello ",(join "bimap world"wrap)
, [ ("startHello ", " world"),
, ("Hellostart", "end world"),
, ("<div style=\"chinese\">Hello", "</div>end"),
, ("<textdiv style=\"chinese\">", "<table/div>"),
, ("<text>", "</table>"),
("<text>", "</table>")
]
]
 
wrap :: String -> Either String Text
wrap x =
if| x `elem` ["start", "end"] = Left x
| otherwise = Right (pack x)</syntaxhighlight>
then Left x
else Right (pack x)
 
main :: IO ()
main = do
mapM_ print $ flip textBetween (head samples) <$> take 3 delims
(putStrLn . unlines) $
zipWith
(\d t -> intercalate (unpack $ textBetween d t) ["\"", "\""])
(drop 3 delims)
(tail samples)</lang>
{{Out}}
<pre>"Rosetta Code"
Line 885 ⟶ 1,382:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">textBetween=: dyad define
text=. y
'start end'=. x
Line 891 ⟶ 1,388:
end=. text"_^:('end'&-:) end
end taketo start takeafter text
)</langsyntaxhighlight>
 
'''Example Usage:'''
<langsyntaxhighlight lang="j"> ('Hello ';' world') textBetween 'Hello Rosetta Code world'
Rosetta Code</langsyntaxhighlight>
 
'''Examples:'''
<langsyntaxhighlight lang="j"> Test_text=: <;._2 noun define
Hello Rosetta Code world
Hello Rosetta Code world
Line 935 ⟶ 1,432:
 
Test_output = Test_delim textBetween&.> Test_text
1 1 1 1 1 1 1 1 1</langsyntaxhighlight>
 
=={{header|Java}}==
Line 943 ⟶ 1,440:
</pre>
 
<langsyntaxhighlight lang="java">
public class textBetween
{
Line 1,005 ⟶ 1,502:
} // end class TextBetween
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">
function textBetween(thisText, startString, endString)
{
Line 1,048 ⟶ 1,545:
return newText;
} // end textBetween
</syntaxhighlight>
</lang>
===ES6===
{{Trans|Haskell}}
Composed from a set of generic functions
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,239 ⟶ 1,736:
)
);
})();</langsyntaxhighlight>
{{Out}}
<pre>[
Line 1,253 ⟶ 1,750:
 
The implementation uses `explode` to ensure arbitrary Unicode will be handled properly.
<syntaxhighlight lang="jq">
<lang jq>
def textbetween_strings($startdlm; $enddlm):
explode
Line 1,268 ⟶ 1,765:
end
| implode;
</syntaxhighlight>
</lang>
=== Verification ===
 
<syntaxhighlight lang="text">
def testdata:
(["Hello Rosetta Code world", "Hello ", " world"],
Line 1,288 ⟶ 1,785:
| $in[0]
| textbetween_strings($in[1]; $in[2])
</syntaxhighlight>
</lang>
===Output===
<syntaxhighlight lang="text">
"Rosetta Code"
"Hello Rosetta Code"
Line 1,300 ⟶ 1,797:
"two fish"
"BarBaz"
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function textbetween(text::AbstractString, startdlm::AbstractString, enddlm::AbstractString)
startind = startdlm != "start" ? last(search(text, startdlm)) + 1 : 1
endind = enddlm != "end" ? first(search(text, enddlm, startind)) - 1 : endof(text)
Line 1,325 ⟶ 1,822:
for (text, s, e) in testcases
println("\nText: ", text, "\nStart delim: ", s, "\nEnd delim: ", e, "\nOutput: ", textbetween(text, s, e))
end</langsyntaxhighlight>
 
{{out}}
Line 1,375 ⟶ 1,872:
=={{header|Kotlin}}==
In the third example, I've assumed that the start delimiter should be "Hello " (not "Hello") to match the required output.
<langsyntaxhighlight lang="scala">// version 1.2.10
 
fun String.textBetween(start: String, end: String): String {
Line 1,419 ⟶ 1,916:
println("Output: \"$b\"\n")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,467 ⟶ 1,964:
Output: "BarBaz"
</pre>
 
=={{header|Lua}}==
French (instead of Chinese) in #4 to avoid off-topic unicode complications. Coded to satisfy this task as worded, though in actual use reader might be better served by directly applying native pattern matching facilities to specific problems.
<syntaxhighlight lang="lua">function textbetween(text, sdelim, edelim)
-- case #5 (end delimiter not present) is only problem for simplest approach, so preprocess:
if not text:find(edelim=="end" and "$" or edelim) then edelim = "end" end
-- then just:
local re = (sdelim=="start" and "^" or sdelim) .. "(.-)" .. (edelim=="end" and "$" or edelim)
return text:match(re) or ""
end
 
function test(text, sdelim, edelim, expected)
print(textbetween(text, sdelim, edelim) == expected)
end
 
test( "Hello Rosetta Code world", "Hello ", " world", "Rosetta Code" )
test( "Hello Rosetta Code world", "start", " world", "Hello Rosetta Code" )
test( "Hello Rosetta Code world", "Hello ", "end", "Rosetta Code world" )
test( "</div><div style=\"french\">bonjour</div>", "<div style=\"french\">", "</div>", "bonjour" )
test( "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>", "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">" )
test( "<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>", "" )
test( "The quick brown fox jumps over the lazy other fox", "quick ", " fox", "brown" )
test( "One fish two fish red fish blue fish", "fish ", " red", "two fish" )
test( "FooBarBazFooBuxQuux", "Foo", "Foo", "BarBaz" )</syntaxhighlight>
{{Out}}
All tests pass, output not given.
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">textBetween := proc(str,delim1,delim2)
local on, off,extra:
on := piecewise(delim1="start", 1, SearchText(delim1, str)):
Line 1,477 ⟶ 2,000:
if off <> 0 then off := off+on+extra-1: end if:
return str[on+extra..off-1]:
end proc:</langsyntaxhighlight>
{{Out|Examples}}
<pre>>textBetween("Hello Rosetta Code world", "Hello ", " world");
Line 1,499 ⟶ 2,022:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">textBetween = function(s, startDelim, endDelim)
startPos = s.indexOf(startDelim) + startDelim.len
if startDelim == "start" then startPos = 0
Line 1,507 ⟶ 2,030:
end function
 
print textBetween("Hello RosettoRosetta Code world", "Hello ", " world")
print textBetween("Hello RosettoRosetta Code world", "start", " world")
print textBetween("Hello RosettoRosetta Code world", "Hello ", "end")
print textBetween("The quick brown fox jumps over the lazy other fox", "quick ", " fox")
print textBetween("FooBarBazFooBuxQuux", "Foo", "Foo")</langsyntaxhighlight>
 
{{out}}
 
<pre>RosettoRosetta Code
Hello RosettoRosetta Code
RosettoRosetta Code world
brown
BarBaz</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils
 
func textBetween(text, startStr, endStr: string): string =
## Return the text between start and end separators.
 
var startIdx = 0
if startStr != "start":
startIdx = text.find(startStr)
if startIdx == -1: return
inc startIdx, startStr.len
 
var endIdx = text.high
if endStr != "end":
endIdx = text.find(endStr, startIdx)
if endIdx == -1: endIdx = text.high
else: dec endIdx
 
result = text.substr(startIdx, endIdx)
 
 
proc quote(s: string): string =
## Return a quoted string, i.e with escaped chars but
## keeping unchanged characters between \128 and \255.
result.addQuoted(s)
 
 
const Data = [
("Hello Rosetta Code world", "Hello ", " world"),
("Hello Rosetta Code world", "start", " world"),
("Hello Rosetta Code world", "Hello ", "end"),
("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>"),
("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>"),
("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>"),
("The quick brown fox jumps over the lazy other fox", "quick ", " fox"),
("One fish two fish red fish blue fish", "fish ", " red"),
("FooBarBazFooBuxQuux", "Foo", "Foo")]
 
for (text, startStr, endStr) in Data:
echo "Text: ", text.quote
echo "Start: ", startStr.quote
echo "End: ", endStr.quote
echo "Output: ", text.textBetween(startStr, endStr).quote
echo()</syntaxhighlight>
 
{{out}}
<pre>Text: "Hello Rosetta Code world"
Start: "Hello "
End: " world"
Result: "Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "start"
End: " world"
Result: "Hello Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "Hello "
End: "end"
Result: "Rosetta Code world"
 
Text: "</div><div style=\"chinese\">你好嗎</div>"
Start: "<div style=\"chinese\">"
End: "</div>"
Result: "你好嗎"
 
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
Start: "<text>"
End: "<table>"
Result: "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
 
Text: "<table style=\"myTable\"><tr><td>hello world</td></tr></table>"
Start: "<table>"
End: "</table>"
Result: ""
 
Text: "The quick brown fox jumps over the lazy other fox"
Start: "quick "
End: " fox"
Result: "brown"
 
Text: "One fish two fish red fish blue fish"
Start: "fish "
End: " red"
Result: "two fish"
 
Text: "FooBarBazFooBuxQuux"
Start: "Foo"
End: "Foo"
Result: "BarBaz"</pre>
 
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class TextBetween {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 3) {
Line 1,564 ⟶ 2,178:
return thisText->SubString(startIndex, endIndex - startIndex);
}
}</langsyntaxhighlight>
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="perl">use feature 'say';
 
sub text_between {
Line 1,609 ⟶ 2,223:
# Ignore start and end delimiter string embedded in longer words
$text = 'Soothe a guilty conscience today, string wrangling is not the best tool to use for this job.';
say '11> '. text_between($text, qr/\bthe /, qr/ to\b/);</langsyntaxhighlight>
{{out}}
<pre>1> Rosetta Code
Line 1,617 ⟶ 2,231:
5> Hello <span>Rosetta Code</span> world</text><table style="myTable">
6>
7> brown
8> two fish
9> BarBaz
10> ll,tta C, w
11> best tool</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2017.12}}
It seems somewhat pointless to write a special purpose routine to do text matching as built-in primitives can do so more flexibly and concisely, but whatever.
 
This version doesn't use strings for meta indexes ('start' and 'end'), rather it accepts regex assertions which are parsed differently from strings. This allows much more robust and fine grained control over what does and doesn't match. (and allows delimiter strings of 'start' and 'end' incidentally.) See the 11th example below which will confound nearly all of the current string-only based implementations.
 
<lang perl6>sub text-between ( $text, $start, $end ) {
return $/»[0]».Str if $text ~~ m:g/ $start (.*?) $end /;
[]
}
 
# Testing
my $text = 'Hello Rosetta Code world';
 
# String start and end delimiter
put '1> ', $text.&text-between( 'Hello ', ' world' );
 
# Regex string start delimiter
put '2> ', $text.&text-between( rx/^/, ' world' );
 
# Regex string end delimiter
put '3> ', $text.&text-between( 'Hello ', rx/$/ );
 
# End delimiter only valid after start delimiter
put '4> ', '</div><div style="chinese">你好嗎</div>'\
.&text-between( '<div style="chinese">', '</div>' );
 
# End delimiter not found, default to string end
put '5> ', '<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">'\
.&text-between( '<text>', rx/'<table>' | $/ );
 
# Start delimiter not found, return blank string
put '6> ', '<table style="myTable"><tr><td>hello world</td></tr></table>'\
.&text-between( '<table>', '</table>' );
 
# Multiple end delimiters, match frugally
put '7> ', 'The quick brown fox jumps over the lazy other fox'\
.&text-between( 'quick ', ' fox' );
 
# Multiple start delimiters, match frugally
put '8> ', 'One fish two fish red fish blue fish'\
.&text-between( 'fish ', ' red' );
 
# Start delimiter is end delimiter
put '9> ', 'FooBarBazFooBuxQuux'\
.&text-between( 'Foo', 'Foo' );
 
# Return all matching strings when multiple matches are possible
put '10> ', join ',', $text.&text-between( 'e', 'o' );
 
# Ignore start and end delimiter string embedded in longer words
put '11> ', 'Soothe a guilty conscience today, string wrangling is not the best tool to use for this job.'\
.&text-between( rx/«'the '/, rx/' to'»/ );</lang>
 
{{out}}
<pre>1> Rosetta Code
2> Hello Rosetta Code
3> Rosetta Code world
4> 你好嗎
5> Hello <span>Rosetta Code</span> world</text><table style="myTable">
6>
7> brown
8> two fish
Line 1,691 ⟶ 2,238:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function text_between(string text, start_delimiter, end_delimiter)
<span style="color: #008080;">function</span> <span style="color: #000000;">text_between</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">)</span>
if start_delimiter!="start" then
<span style="color: #008080;">if</span> <span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">"start"</span> <span style="color: #008080;">then</span>
integer k = match(start_delimiter,text)
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
if k=0 then return "" end if
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008000;">""</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
text = text[k+length(start_delimiter)..$]
<span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">)..$]</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if end_delimiter!="end" then
<span style="color: #008080;">if</span> <span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">"end"</span> <span style="color: #008080;">then</span>
integer k = match(end_delimiter,text)
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
if k!=0 then
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
text = text[1..k-1]
<span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return text
<span style="color: #008080;">return</span> <span style="color: #000000;">text</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
constant tests = {
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
{"Hello Rosetta Code world","Hello "," world","Rosetta Code"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Hello Rosetta Code world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hello "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rosetta Code"</span><span style="color: #0000FF;">},</span>
{"Hello Rosetta Code world","start"," world","Hello Rosetta Code"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Hello Rosetta Code world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"start"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hello Rosetta Code"</span><span style="color: #0000FF;">},</span>
{"Hello Rosetta Code world","Hello ","end","Rosetta Code world"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Hello Rosetta Code world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hello "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"end"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rosetta Code world"</span><span style="color: #0000FF;">},</span>
{"</div><div style=\"french\">bonjour</div>","<div style=\"french\">","</div>","bonjour"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"&lt;/div&gt;&lt;div style=\"french\"&gt;bonjour&lt;/div&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;div style=\"french\"&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;/div&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bonjour"</span><span style="color: #0000FF;">},</span>
{"<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">","<text>","<table>",
<span style="color: #0000FF;">{</span><span style="color: #008000;">"&lt;text&gt;Hello &lt;span&gt;Rosetta Code&lt;/span&gt; world&lt;/text&gt;&lt;table style=\"myTable\"&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;text&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;table&gt;"</span><span style="color: #0000FF;">,</span>
"Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"},
<span style="color: #008000;">"Hello &lt;span&gt;Rosetta Code&lt;/span&gt; world&lt;/text&gt;&lt;table style=\"myTable\"&gt;"</span><span style="color: #0000FF;">},</span>
{"<table style=\"myTable\"><tr><td>hello world</td></tr></table>","<table>","</table>",""},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"&lt;table style=\"myTable\"&gt;&lt;tr&gt;&lt;td&gt;hello world&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;table&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"&lt;/table&gt;"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span>
{"The quick brown fox jumps over the lazy other fox","quick "," fox","brown"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"The quick brown fox jumps over the lazy other fox"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"quick "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" fox"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"brown"</span><span style="color: #0000FF;">},</span>
{"One fish two fish red fish blue fish","fish "," red","two fish"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"One fish two fish red fish blue fish"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"fish "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" red"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"two fish"</span><span style="color: #0000FF;">},</span>
{"FooBarBazFooBuxQuux","Foo","Foo","BarBaz"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"FooBarBazFooBuxQuux"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Foo"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Foo"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"BarBaz"</span><span style="color: #0000FF;">},</span>
{"Hello Rosetta Code world","start","end","Hello Rosetta Code world"}}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Hello Rosetta Code world"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"start"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"end"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hello Rosetta Code world"</span><span style="color: #0000FF;">}}</span>
 
constant fmt = """
<span style="color: #008080;">constant</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Text: "%s"
Start delimiter Text: "%s"
End Start delimiter: "%s"
Output End delimiter: "%s"
Expect Output: "%s" ***ERROR***
Expect: "%s" ***ERROR***
 
"""
"""</span>
 
for i=1 to length(tests) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string {text,start_delimiter,end_delimiter,expected} = tests[i],
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">expected</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
actual = text_between(text,start_delimiter,end_delimiter)
<span style="color: #004080;">string</span> <span style="color: #000000;">actual</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text_between</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">)</span>
if actual!=expected then
<span style="color: #008080;">if</span> <span style="color: #000000;">actual</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">expected</span> <span style="color: #008080;">then</span>
printf(1,fmt,{text,start_delimiter,end_delimiter,actual,expected})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">start_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">end_delimiter</span><span style="color: #0000FF;">,</span><span style="color: #000000;">actual</span><span style="color: #0000FF;">,</span><span style="color: #000000;">expected</span><span style="color: #0000FF;">})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
All tests pass, so no output.
Line 1,743 ⟶ 2,292:
</pre>
 
<langsyntaxhighlight lang="php">
<?php
function text_between($string, $start, $end)
Line 1,789 ⟶ 2,338:
print_r($returnText);
?>
</syntaxhighlight>
</lang>
 
=={{header|PowerBASIC}}==
<langsyntaxhighlight lang="powerbasic">#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
Line 1,911 ⟶ 2,460:
CON.PRINT IIF$(TextBetween(sText, StartDelim, EndDelim) = Expected, "OK", "failed")
 
END FUNCTION</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
#!/usr/bin/env python
from sys import argv
Line 1,960 ⟶ 2,509:
 
print textBetween( thisText, startString, endString )
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ dup $ "start" = iff
drop done
tuck over findseq
tuck over found iff
[ unrot dip size +
split nip ]
done
2drop drop $ "" ] is from-start ( $ $ --> $ )
 
[ dup $ "end" = iff drop done
over findseq split drop ] is to-end ( $ $ --> $ )
 
[ dip from-start to-end ] is between ( $ $ $ --> $ )
 
[ char " tuck join join
echo$ cr ] is quote$ ( $ --> )
 
[ 3 pack dup
dip unpack unpack
rot say " Text: " quote$
swap say " Start: " quote$
say " End: " quote$
between
say "Result: " quote$
cr ] is task ( $ $ $ --> $ )
 
$ "Hello Rosetta Code world" $ "Hello " $ " world" task
$ "Hello Rosetta Code world" $ "start" $ " world" task
$ "Hello Rosetta Code world" $ "Hello " $ "end" task
$ "Hello Rosetta Code world" $ "Hello " $ "end" task
$ '</div><div style=\"chinese\">???</div>'
$ '<div style=\"chinese\">' $ "</div>" task
$ '<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">'
$ "<text>" $ "<table>" task
$ '<table style=\"myTable\"><tr><td>hello world</td></tr></table>'
$ "<table>" $ "</table>" task
$ "The quick brown fox jumps over the lazy other fox"
$ "quick " $ " fox" task
$ "One fish two fish red fish blue fish"
$ "fish " $ " red" task
$ "FooBarBazFooBuxQuux" $ "Foo" $ "Foo" task</syntaxhighlight>
 
{{out}}
 
<pre style="scroll: overflow; height: 20em"> Text: "Hello Rosetta Code world"
Start: "Hello "
End: " world"
Result: "Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "start"
End: " world"
Result: "Hello Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "Hello "
End: "end"
Result: "Rosetta Code world"
 
Text: "Hello Rosetta Code world"
Start: "Hello "
End: "end"
Result: "Rosetta Code world"
 
Text: "</div><div style=\"chinese\">???</div>"
Start: "<div style=\"chinese\">"
End: "</div>"
Result: "???"
 
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
Start: "<text>"
End: "<table>"
Result: "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
 
Text: "<table style=\"myTable\"><tr><td>hello world</td></tr></table>"
Start: "<table>"
End: "</table>"
Result: ""
 
Text: "The quick brown fox jumps over the lazy other fox"
Start: "quick "
End: " fox"
Result: "brown"
 
Text: "One fish two fish red fish blue fish"
Start: "fish "
End: " red"
Result: "two fish"
 
Text: "FooBarBazFooBuxQuux"
Start: "Foo"
End: "Foo"
Result: "BarBaz"</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(require (prefix-in 13: srfi/13))
 
Line 1,995 ⟶ 2,640:
(test-case "The quick brown fox jumps over the lazy other fox" "quick " " fox" "brown")
(test-case "One fish two fish red fish blue fish" "fish " " red" "two fish")
(test-case "FooBarBazFooBuxQuux" "Foo" "Foo" "BarBaz"))</langsyntaxhighlight>
{{out}}
All tests pass, so no output.
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.12}}
It seems somewhat pointless to write a special purpose routine to do text matching as built-in primitives can do so more flexibly and concisely, but whatever.
 
This version doesn't use strings for meta indexes ('start' and 'end'), rather it accepts regex assertions which are parsed differently from strings. This allows much more robust and fine grained control over what does and doesn't match. (and allows delimiter strings of 'start' and 'end' incidentally.) See the 11th example below which will confound nearly all of the current string-only based implementations.
 
<syntaxhighlight lang="raku" line>sub text-between ( $text, $start, $end ) {
return $/»[0]».Str if $text ~~ m:g/ $start (.*?) $end /;
[]
}
 
# Testing
my $text = 'Hello Rosetta Code world';
 
# String start and end delimiter
put '1> ', $text.&text-between( 'Hello ', ' world' );
 
# Regex string start delimiter
put '2> ', $text.&text-between( rx/^/, ' world' );
 
# Regex string end delimiter
put '3> ', $text.&text-between( 'Hello ', rx/$/ );
 
# End delimiter only valid after start delimiter
put '4> ', '</div><div style="chinese">你好嗎</div>'\
.&text-between( '<div style="chinese">', '</div>' );
 
# End delimiter not found, default to string end
put '5> ', '<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">'\
.&text-between( '<text>', rx/'<table>' | $/ );
 
# Start delimiter not found, return blank string
put '6> ', '<table style="myTable"><tr><td>hello world</td></tr></table>'\
.&text-between( '<table>', '</table>' );
 
# Multiple end delimiters, match frugally
put '7> ', 'The quick brown fox jumps over the lazy other fox'\
.&text-between( 'quick ', ' fox' );
 
# Multiple start delimiters, match frugally
put '8> ', 'One fish two fish red fish blue fish'\
.&text-between( 'fish ', ' red' );
 
# Start delimiter is end delimiter
put '9> ', 'FooBarBazFooBuxQuux'\
.&text-between( 'Foo', 'Foo' );
 
# Return all matching strings when multiple matches are possible
put '10> ', join ',', $text.&text-between( 'e', 'o' );
 
# Ignore start and end delimiter string embedded in longer words
put '11> ', 'Soothe a guilty conscience today, string wrangling is not the best tool to use for this job.'\
.&text-between( rx/«'the '/, rx/' to'»/ );</syntaxhighlight>
 
{{out}}
<pre>1> Rosetta Code
2> Hello Rosetta Code
3> Rosetta Code world
4> 你好嗎
5> Hello <span>Rosetta Code</span> world</text><table style="myTable">
6>
7> brown
8> two fish
9> BarBaz
10> ll,tta C, w
11> best tool</pre>
 
=={{header|REXX}}==
===version 1===
{{trans|Kotlin}}
<syntaxhighlight lang="rexx">
<lang rexx>Call test "Hello Rosetta Code world","Hello "," world"
/*REXX*/
 
Call test "Hello Rosetta Code world","Hello "," world"
Call test "Hello Rosetta Code world","start"," world"
Call test "Hello Rosetta Code world","Hello ","end"
Line 2,043 ⟶ 2,759:
End
 
o: Say arg(1) </langsyntaxhighlight>
{{out|Output}}
<pre>Text: "Hello Rosetta Code world"
Line 2,095 ⟶ 2,811:
Also, it wasn't necessary, but I <u>assummed</u> (bad assumption?) that the &nbsp; <big>'''\'''</big> &nbsp; could be an escape character, but unless clarified,
<br>it's being treated as a commom character, &nbsp; REXX has no need for escape characters (within character strings).
<langsyntaxhighlight lang="rexx">/*REXX programs displays the text between two text deliminiters in a target text string.*/
call TB 'Hello Rosetta Code world', "Hello ", ' world'
call TB 'Hello Rosetta Code world', "start", ' world'
Line 2,114 ⟶ 2,830:
if E\=='end' then parse var $ $ (E) /* " " before " END. " */
say ' Output: "'$'"' /*display the extracted string to term.*/
return</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,164 ⟶ 2,880:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Text between
 
Line 2,210 ⟶ 2,926:
next
see '"' + substr(list2str(textdel), nl, " ") +'"' + nl + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,231 ⟶ 2,947:
Output = "Rosetta Code world"
</pre>
 
=={{header|RPL}}==
{{works with|HP|48G}}
« → start end
« '''CASE'''
start "start" == '''THEN''' 1 '''END'''
DUP start POS '''THEN''' LASTARG start SIZE + '''END'''
DUP SIZE 1 +
'''END'''
OVER SIZE SUB
1 OVER end POS 1 -
'''IF''' DUP 0 < end "end" == OR '''THEN''' DROP OVER SIZE '''END'''
SUB
» » '<span style="color:blue">BTWN</span>' STO <span style="color:grey">''@ ( "text" "start" "end" -- "text_between" )''</span>
 
=={{header|Ruby}}==
Test
<langsyntaxhighlight lang="ruby">
class String
def textBetween startDelimiter, endDelimiter
Line 2,280 ⟶ 3,010:
 
puts returnText
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
//Use Into<String> so input can be String, &str or anything else that implements Into<String>
fn text_between<S: Into<String>>(input: S, start: S, end: S) -> String {
Line 2,321 ⟶ 3,052:
println!("'{}'", text_between("FooBarBazFooBuxQuux", "Foo", "Foo"));
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,334 ⟶ 3,065:
'BarBaz'
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object TextBetween extends App {
val (thisText, startDelimiter, endDelimiter) = (args(0), args(1),args(2))
 
Line 2,361 ⟶ 3,093:
println(textBetween(thisText, startDelimiter, endDelimiter))
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
Uses /^/ and /$/ as start and end delimiters. Additionally, the start and end delimiters can be regular expressions.
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">func text_between (text, beg, end) {
 
beg.escape! if beg.kind_of(String)
Line 2,435 ⟶ 3,167:
assert_eq(t{:out}, r)
say "text_between(#{t{:text}.dump}, #{t{:start}.dump}, #{t{:end}.dump}) = #{r.dump}"
}</langsyntaxhighlight>
{{out}}<pre>
text_between("Hello Rosetta Code world", "Hello ", " world") = "Rosetta Code"
Line 2,446 ⟶ 3,178:
text_between("One fish two fish red fish blue fish", "fish ", " red") = "two fish"
text_between("FooBarBazFooBuxQuux", "Foo", "Foo") = "BarBaz"</pre>
 
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
* Program: text_between.sbl
* To run: sbl -r text_between.sbl
* Description: Get the text in a string that occurs between
* a start and end delimiter. Programs will be given a search string,
* a start delimiter string, and an end delimiter string. The delimiters
* will not be unset, and will not be the empty string.
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
 
lf = substr(&alphabet,11,1) ;* New line or line feed
 
 
* Function text_between will return the text between start and end delimiters,
* where start can be the word 'start' for the beginning of the text,
* and end can be the word 'end' for the end of the text.
define('text_between(text,start,end)sb,eb')
:(text_between_end)
text_between
sb = (ident(start,'start') pos(0), breakx(substr(start,1,1)) start)
eb = (ident(end,'end') rem . text_between, (arb . text_between end) | (rem . text_between) )
text ? sb eb
:(return)
text_between_end
 
 
* Read text lines after the END statement
in1
line = input :f(in1end)
line ? break('|') . text '|' break('|') . start '|' rem . end
output = lf 'Text: "' text '"'
output = 'Start: "' start '"'
output = 'End: "' end '"'
text_between = text_between(text,start,end)
output = 'Output: "' text_between '"'
:(in1)
in1end
 
END
Hello Rosetta Code world|Hello | world
Hello Rosetta Code world|start| world
Hello Rosetta Code world|Hello |end
</div><div style=\"chinese\">你好嗎</div>|<div style=\"chinese\">|</div>
<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">|<text>|<table>
<table style=\"myTable\"><tr><td>hello world</td></tr></table>|<table>|</table>
The quick brown fox jumps over the lazy other fox|quick | fox
One fish two fish red fish blue fish|fish | red
FooBarBazFooBuxQuux|Foo|Foo
</syntaxhighlight>
{{out}}
<pre>
Text: "Hello Rosetta Code world"
Start: "Hello "
End: " world"
Output: "Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "start"
End: " world"
Output: "Hello Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start: "Hello "
End: "end"
Output: "Rosetta Code world"
 
Text: "</div><div style=\"chinese\">你好嗎</div>"
Start: "<div style=\"chinese\">"
End: "</div>"
Output: "你好嗎"
 
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
Start: "<text>"
End: "<table>"
Output: "Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">"
 
Text: "<table style=\"myTable\"><tr><td>hello world</td></tr></table>"
Start: "<table>"
End: "</table>"
Output: ""
 
Text: "The quick brown fox jumps over the lazy other fox"
Start: "quick "
End: " fox"
Output: "brown"
 
Text: "One fish two fish red fish blue fish"
Start: "fish "
End: " red"
Output: "two fish"
 
Text: "FooBarBazFooBuxQuux"
Start: "Foo"
End: "Foo"
Output: "BarBaz"
</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">import Foundation
 
public extension String {
func textBetween(_ startDelim: String, and endDelim: String) -> String {
precondition(!startDelim.isEmpty && !endDelim.isEmpty)
 
let startIdx: String.Index
let endIdx: String.Index
 
if startDelim == "start" {
startIdx = startIndex
} else if let r = range(of: startDelim) {
startIdx = r.upperBound
} else {
return ""
}
 
if endDelim == "end" {
endIdx = endIndex
} else if let r = self[startIdx...].range(of: endDelim) {
endIdx = r.lowerBound
} else {
endIdx = endIndex
}
 
return String(self[startIdx..<endIdx])
}
}
 
let tests = [
("Hello Rosetta Code world", "Hello ", " world"),
("Hello Rosetta Code world", "start", " world"),
("Hello Rosetta Code world", "Hello ", "end"),
("</div><div style=\"chinese\">你好嗎</div>", "<div style=\"chinese\">", "</div>"),
("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>"),
("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>"),
("The quick brown fox jumps over the lazy other fox", "quick ", " fox"),
("One fish two fish red fish blue fish", "fish ", " red"),
("FooBarBazFooBuxQuux", "Foo", "Foo")
]
 
for (input, start, end) in tests {
print("Input: \"\(input)\"")
print("Start delimiter: \"\(start)\"")
print("End delimiter: \"\(end)\"")
print("Text between: \"\(input.textBetween(start, and: end))\"\n")
}</syntaxhighlight>
 
{{out}}
 
<pre style="scroll: overflow; height: 20em">Input: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: " world"
Text between: "Rosetta Code"
 
Input: "Hello Rosetta Code world"
Start delimiter: "start"
End delimiter: " world"
Text between: "Hello Rosetta Code"
 
Input: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: "end"
Text between: "Rosetta Code world"
 
Input: "</div><div style="chinese">你好嗎</div>"
Start delimiter: "<div style="chinese">"
End delimiter: "</div>"
Text between: "你好嗎"
 
Input: "<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">"
Start delimiter: "<text>"
End delimiter: "<table>"
Text between: "Hello <span>Rosetta Code</span> world</text><table style="myTable">"
 
Input: "<table style="myTable"><tr><td>hello world</td></tr></table>"
Start delimiter: "<table>"
End delimiter: "</table>"
Text between: ""
 
Input: "The quick brown fox jumps over the lazy other fox"
Start delimiter: "quick "
End delimiter: " fox"
Text between: "brown"
 
Input: "One fish two fish red fish blue fish"
Start delimiter: "fish "
End delimiter: " red"
Text between: "two fish"
 
Input: "FooBarBazFooBuxQuux"
Start delimiter: "Foo"
End delimiter: "Foo"
Text between: "BarBaz"</pre>
 
=={{header|Tcl}}==
 
<syntaxhighlight lang="tcl">package require Tcl 8.5
 
proc between {str start end} {
set f [string first $start $str ]
if {$f < 0} { return "" }
incr f [string length $start]
set e [string first $end $str $f]
return [string range $str $f [expr {($e < 0) ? "end" : $e-1}]]
}
 
## data is taken from "Factor"
set L {
{ "Hello Rosetta Code world" "Hello " " world" }
{ "Hello Rosetta Code world" "start" " world" }
{ "Hello Rosetta Code world" "Hello " "end" }
{ "</div><div style=\"chinese\">你好嗎</div>" "<div style=\"chinese\">" "</div>" }
{ "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">" "<text>" "<table>" }
{ "<table style=\"myTable\"><tr><td>hello world</td></tr></table>" "<table>" "</table>" }
{ "The quick brown fox jumps over the lazy other fox" "quick " " fox" }
{ "One fish two fish red fish blue fish" "fish " " red" }
{ "FooBarBazFooBuxQuux" "Foo" "Foo" }
}
 
foreach x $L {
puts " "
lappend x [between {*}$x]
foreach v $x t { "Text" "Start delimiter" "End delimiter" "Output" } {
puts " [format %15s $t]: $v"
}
}</syntaxhighlight>
 
{{out}}
<pre style="scroll: overflow; height: 20em">
Text: Hello Rosetta Code world
Start delimiter: Hello
End delimiter: world
Output: Rosetta Code
Text: Hello Rosetta Code world
Start delimiter: start
End delimiter: world
Output:
Text: Hello Rosetta Code world
Start delimiter: Hello
End delimiter: end
Output: Rosetta Code world
Text: </div><div style="chinese">你好嗎</div>
Start delimiter: <div style="chinese">
End delimiter: </div>
Output: 你好嗎
Text: <text>Hello <span>Rosetta Code</span> world</text><table style="myTable">
Start delimiter: <text>
End delimiter: <table>
Output: Hello <span>Rosetta Code</span> world</text><table style="myTable">
Text: <table style="myTable"><tr><td>hello world</td></tr></table>
Start delimiter: <table>
End delimiter: </table>
Output:
Text: The quick brown fox jumps over the lazy other fox
Start delimiter: quick
End delimiter: fox
Output: brown
Text: One fish two fish red fish blue fish
Start delimiter: fish
End delimiter: red
Output: two fish
Text: FooBarBazFooBuxQuux
Start delimiter: Foo
End delimiter: Foo
Output: BarBaz
</pre>
 
=={{header|UNIX Shell}}==
Line 2,458 ⟶ 3,466:
The "hard" assertions when unpacking the arguments to the "text_between" function reflect the assumptions in the requirements for this problem: that null/empty arguments will never be provided. If any empty arguments are given, the interpreter running this function will exit after printing an error. If this function is invoked without a subshell, that will crash the invoking program as well. In practical use, that may not be desirable, in which case the ":?" assertions should be replaced with less harsh conditional-unpack code (e.g. <code>if [ -z "${1:-}" ]; then echo "Invalid input!" && return 127; else local var="$1"; fi</code>).
 
<langsyntaxhighlight lang="bash">text_between() {
local search="${1:?Search text not provided}"
local start_str="${2:?Start text not provided}"
Line 2,490 ⟶ 3,498:
text_between "Hello Rosetta Code world" "Hello " " world"
text_between "Hello Rosetta Code world" "start" " world"
text_between "Hello Rosetta Code world" "Hello " "end"</langsyntaxhighlight>
 
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Private Const STRING_START As String = "Start"
Line 2,582 ⟶ 3,589:
Text_Between = Mid(T, Len(F) + InStr(T, F), InStr(InStr(T, F), T, L) - (Len(F) + InStr(T, F)))
End Select
End Function</langsyntaxhighlight>
{{out}}
<pre>1- Rosetta Code
Line 2,599 ⟶ 3,606:
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Public Function TextBetween(ByVal Text As String, ByVal StartDelim As String, ByVal EndDelim As String) As String
Dim indS As Long
Dim indE As Long
Line 2,707 ⟶ 3,714:
Text = StartDelim & Expected & EndDelim & "FooBuxQuux"
Debug.Assert TextBetween(Text, StartDelim, EndDelim) = Expected
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
Function TextBetween(source As String, pre As String, suf As String) As String
Dim startIndex As Integer
 
If pre = "start" Then
startIndex = 0
Else
startIndex = source.IndexOf(pre)
If startIndex < 0 Then
Return ""
End If
startIndex += pre.Length
End If
 
Dim endIndex = source.IndexOf(suf, startIndex)
If endIndex < 0 OrElse suf = "end" Then
Return source.Substring(startIndex)
End If
Return source.Substring(startIndex, endIndex - startIndex)
End Function
 
Sub Print(s As String, b As String, e As String)
Console.WriteLine("text: '{0}'", s)
Console.WriteLine("start: '{0}'", b)
Console.WriteLine("end: '{0}'", e)
Console.WriteLine("result: '{0}'", TextBetween(s, b, e))
Console.WriteLine()
End Sub
 
Sub Main()
Console.OutputEncoding = System.Text.Encoding.UTF8
 
Print("Hello Rosetta Code world", "Hello ", " world")
Print("Hello Rosetta Code world", "start", " world")
Print("Hello Rosetta Code world", "Hello ", "end")
Print("</div><div style=""chinese"">你好嗎</div>", "<div style=""chinese"">", "</div>")
Print("<text>Hello <span>Rosetta Code</span> world</text><table style=""myTable"">", "<text>", "<table>")
Print("<table style=""myTable""><tr><td>hello world</td></tr></table>", "<table>", "</table>")
Print("The quick brown fox jumps over the lazy other fox", "quick ", " fox")
Print("One fish two fish red fish blue fish", "fish ", " red")
Print("FooBarBazFooBuxQuux", "Foo", "Foo")
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>text: 'Hello Rosetta Code world'
start: 'Hello '
end: ' world'
result: 'Rosetta Code'
 
text: 'Hello Rosetta Code world'
start: 'start'
end: ' world'
result: 'Hello Rosetta Code'
 
text: 'Hello Rosetta Code world'
start: 'Hello '
end: 'end'
result: 'Rosetta Code world'
 
text: '</div><div style="chinese">你好嗎</div>'
start: '<div style="chinese">'
end: '</div>'
result: '你好嗎'
 
text: '<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">'
start: '<text>'
end: '<table>'
result: 'Hello <span>Rosetta Code</span> world</text><table style="myTable">'
 
text: '<table style="myTable"><tr><td>hello world</td></tr></table>'
start: '<table>'
end: '</table>'
result: ''
 
text: 'The quick brown fox jumps over the lazy other fox'
start: 'quick '
end: ' fox'
result: 'brown'
 
text: 'One fish two fish red fish blue fish'
start: 'fish '
end: ' red'
result: 'two fish'
 
text: 'FooBarBazFooBuxQuux'
start: 'Foo'
end: 'Foo'
result: 'BarBaz'</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn text_between(str string, start string, end string) string {
if str == "" || start == "" || end == "" {
return str
}
mut s := 0
if start != "start" {
s = str.index(start) or {-1}
}
if s == -1 {
return ""
}
mut si := 0
if start != "start" {
si = s + start.len
}
mut e := str.len
if end != "end" {
e = str[si..].index(end) or {-1}
if e == -1 {
return str[si..]
}
e += si
}
return str[si..e]
}
fn main() {
texts := [
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"</div><div style=\"chinese\">你好嗎</div>",
"<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">",
"<table style=\"myTable\"><tr><td>hello world</td></tr></table>",
"The quick brown fox jumps over the lazy other fox",
"One fish two fish red fish blue fish",
"FooBarBazFooBuxQuux",
]
starts:= [
"Hello ", "start", "Hello ", "<div style=\"chinese\">",
"<text>", "<table>", "quick ", "fish ", "Foo",
]
ends := [
" world", " world", "end", "</div>", "<table>",
"</table>", " fox", " red", "Foo",
]
for i, text in texts {
println("Text: \"$text\"")
println("Start delimiter: \"${starts[i]}\"")
println("End delimiter: \"${ends[i]}\"")
b := text_between(text, starts[i], ends[i])
println("Output: \"$b\"\n")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Text: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: " world"
Output: "Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start delimiter: "start"
End delimiter: " world"
Output: "Hello Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: "end"
Output: "Rosetta Code world"
 
Text: "</div><div style="chinese">你好嗎</div>"
Start delimiter: "<div style="chinese">"
End delimiter: "</div>"
Output: "你好嗎"
 
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">"
Start delimiter: "<text>"
End delimiter: "<table>"
Output: "Hello <span>Rosetta Code</span> world</text><table style="myTable">"
 
Text: "<table style="myTable"><tr><td>hello world</td></tr></table>"
Start delimiter: "<table>"
End delimiter: "</table>"
Output: ""
 
Text: "The quick brown fox jumps over the lazy other fox"
Start delimiter: "quick "
End delimiter: " fox"
Output: "brown"
 
Text: "One fish two fish red fish blue fish"
Start delimiter: "fish "
End delimiter: " red"
Output: "two fish"
 
Text: "FooBarBazFooBuxQuux"
Start delimiter: "Foo"
End delimiter: "Foo"
Output: "BarBaz"
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var textBetween = Fn.new { |str, start, end|
if (!((start is String) && start != "") && !((end is String) && end != "")) {
Fiber.abort("Start and end must both be non-empty strings.")
}
if (str == "") return str
var s = (start == "start") ? 0 : str.indexOf(start)
if (s == -1) return ""
var si = (start == "start") ? 0 : s + start.count
var e = (end == "end") ? str.count : str.indexOf(end, si)
if (e == -1) return str[si..-1]
return str[si...e]
}
 
var texts = [
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"</div><div style=\"chinese\">你好嗎</div>",
"<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">",
"<table style=\"myTable\"><tr><td>hello world</td></tr></table>",
"The quick brown fox jumps over the lazy other fox",
"One fish two fish red fish blue fish",
"FooBarBazFooBuxQuux"
]
 
var starts = [
"Hello ", "start", "Hello ", "<div style=\"chinese\">",
"<text>", "<table>", "quick ", "fish ", "Foo"
]
 
var ends = [
" world", " world", "end", "</div>", "<table>",
"</table>", " fox", " red", "Foo"
]
 
var i = 0
for (text in texts) {
Fmt.print("Text: $q", text)
Fmt.print("Start delimiter: $q", starts[i])
Fmt.print("End delimiter: $q", ends[i])
var b = textBetween.call(text, starts[i], ends[i])
Fmt.print("Output: $q\n", b)
i = i + 1
}</syntaxhighlight>
 
{{out}}
<pre>
Text: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: " world"
Output: "Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start delimiter: "start"
End delimiter: " world"
Output: "Hello Rosetta Code"
 
Text: "Hello Rosetta Code world"
Start delimiter: "Hello "
End delimiter: "end"
Output: "Rosetta Code world"
 
Text: "</div><div style="chinese">你好嗎</div>"
Start delimiter: "<div style="chinese">"
End delimiter: "</div>"
Output: "你好嗎"
 
Text: "<text>Hello <span>Rosetta Code</span> world</text><table style="myTable">"
Start delimiter: "<text>"
End delimiter: "<table>"
Output: "Hello <span>Rosetta Code</span> world</text><table style="myTable">"
 
Text: "<table style="myTable"><tr><td>hello world</td></tr></table>"
Start delimiter: "<table>"
End delimiter: "</table>"
Output: ""
 
Text: "The quick brown fox jumps over the lazy other fox"
Start delimiter: "quick "
End delimiter: " fox"
Output: "brown"
 
Text: "One fish two fish red fish blue fish"
Start delimiter: "fish "
End delimiter: " red"
Output: "two fish"
 
Text: "FooBarBazFooBuxQuux"
Start delimiter: "Foo"
End delimiter: "Foo"
Output: "BarBaz"
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">include xpllib; \for StrFind, StrLen, Print
 
proc TextBetween(Str, StartStr, EndStr);
char Str, StartStr, EndStr;
int EndInx, I, Addr;
[if StrFind(StartStr, "start") = 0 then \another delimiter is given
[Addr:= StrFind(Str, StartStr);
if Addr # 0 then \if delimiter found then
Str:= Addr + StrLen(StartStr) \ start output string after it
else Str:= Str + StrLen(Str);
];
EndInx:= StrLen(Str) - 1;
if StrFind(EndStr, "end") = 0 then \another delimiter is given
[Addr:= StrFind(Str, EndStr);
if Addr # 0 then \if delimiter found then
EndInx:= Addr - Str - 1; \ end output string before it
];
ChOut(0, ^");
for I:= 0 to EndInx do
ChOut(0, Str(I));
ChOut(0, ^"); CrLf(0);
];
 
int Texts, Starts, Ends, I;
[Texts:= [
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"Hello Rosetta Code world",
"</div><div style=^"chinese^">你好嗎</div>",
"<text>Hello <span>Rosetta Code</span> world</text><table style=^"myTable^">",
"<table style=^"myTable^"><tr><td>hello world</td></tr></table>",
"The quick brown fox jumps over the lazy other fox",
"One fish two fish red fish blue fish",
"FooBarBazFooBuxQuux"];
Starts:= [
"Hello ", "start", "Hello ", "<div style=^"chinese^">",
"<text>", "<table>", "quick ", "fish ", "Foo"];
Ends:= [
" world", " world", "end", "</div>",
"<table>", "</table>", " fox", " red", "Foo"];
for I:= 0 to 9-1 do
[Print("Example %d: ", I+1);
TextBetween(Texts(I), Starts(I), Ends(I));
];
]</syntaxhighlight>
{{out}}
<pre>
Example 1: "Rosetta Code"
Example 2: "Hello Rosetta Code"
Example 3: "Rosetta Code world"
Example 4: "你好嗎"
Example 5: "Hello <span>Rosetta Code</span> world</text><table style="myTable">"
Example 6: ""
Example 7: "brown"
Example 8: "two fish"
Example 9: "BarBaz"
</pre>
 
=={{header|Yabasic}}==
{{trans|Wren}}
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Text_between
// by Galileo, 04/2022
 
sub textBetween$(string$, start$, end$)
local s, si, e, ls
if start$ = "" and end$ = "" return "Start and end must both be non-empty strings."
if (string$ == "") return string$
if start$ = "start" then s = 1 else s = instr(string$, start$) end if
if s = 0 return ""
if start$ = "start" then si = 1 else si = s + len(start$) end if
ls = len(string$)
if end$ = "end" then e = ls + 1 else e = instr(string$, end$, si) end if
if e = 0 return right$(string$, ls - si + 1)
return mid$(string$, si, e - si)
end sub
data "Hello Rosetta Code world", "Hello", "world"
data "Hello Rosetta Code world", "start", "world"
data "Hello Rosetta Code world", "Hello", "end"
data "</div><div style=\"chinese\">???</div>", "<div style=\"chinese\">", "</div>"
data "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>"
data "<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>"
data "The quick brown fox jumps over the lazy other fox", "quick ", " fox"
data "One fish two fish red fish blue fish", "fish ", " red"
data "FooBarBazFooBuxQuux", "Foo", "Foo"
data ""
do
read text$
if text$ = "" break
print "Text: ", text$
read start$
print "Start delimiter: ", start$
read end$
print "End delimiter: ", end$
print "Output: ", textBetween$(text$, start$, end$), "\n"
loop</syntaxhighlight>
{{out}}
<pre>Text: Hello Rosetta Code world
Start delimiter: Hello
End delimiter: world
Output: Rosetta Code
 
Text: Hello Rosetta Code world
Start delimiter: start
End delimiter: world
Output: Hello Rosetta Code
 
Text: Hello Rosetta Code world
Start delimiter: Hello
End delimiter: end
Output: Rosetta Code world
 
Text: </div><div style="chinese">???</div>
Start delimiter: <div style="chinese">
End delimiter: </div>
Output: ???
 
Text: <text>Hello <span>Rosetta Code</span> world</text><table style="myTable">
Start delimiter: <text>
End delimiter: <table>
Output: Hello <span>Rosetta Code</span> world</text><table style="myTable">
 
Text: <table style="myTable"><tr><td>hello world</td></tr></table>
Start delimiter: <table>
End delimiter: </table>
Output:
 
Text: The quick brown fox jumps over the lazy other fox
Start delimiter: quick
End delimiter: fox
Output: brown
 
Text: One fish two fish red fish blue fish
Start delimiter: fish
End delimiter: red
Output: two fish
 
Text: FooBarBazFooBuxQuux
Start delimiter: Foo
End delimiter: Foo
Output: BarBaz
 
---Program done, press RETURN---</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn getText(text,start,end){
s = (if((s:=text.find(start))==Void) 0 else s + start.len());
e = (if((e:=text.find(end,s))==Void) text.len() else e);
Line 2,717 ⟶ 4,166:
getText("Hello Rosetta Code world","Hello "," world").println();
getText("Hello Rosetta Code world","start", " world").println();
getText("Hello Rosetta Code world","Hello", "end" ).println();</langsyntaxhighlight>
{{out}}
<pre>
9,477

edits