Strip comments from a string: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(25 intermediate revisions by 18 users not shown) | |||
Line 31:
=={{header|11l}}==
<
V? p = line.find(sep)
I p != N
Line 39:
print(remove_comments(‘apples ; pears # and bananas’, (‘;’, ‘#’)))
print(remove_comments(‘apples ; pears # and bananas’, ‘#’))
print(remove_comments(‘apples ; pears # and bananas’, ‘!’))</
{{out}}
Line 46:
apples ; pears
apples ; pears # and bananas
</pre>
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">StripComments:
;prints a string but stops at the comment character
;INPUT: D7 = comment character(s) of choice
;A0 = source address of string
;up to four can be used, each takes up a different 8 bits of the register
;to omit an argument, leave its bits as zero.
.loop:
MOVE.B (A0)+,D0
CMP.B #0,D0 ;check for null terminator
beq .done
CMP.B D7,D0 ;check the first comment char
beq .done
ROR.L #8,D7
CMP.B D7,D0 ;check the second comment char
beq .done
ROR.L #8,D7
CMP.B D7,D0 ;check the third comment char
beq .done
ROR.L #8,D7
CMP.B D7,D0 ;check the fourth comment char
beq .done
ROR.L #8,D7
CMP.B #' ',D0
BNE dontCheckNext
MOVE.B (A0),D1 ;look ahead one character, if that character is a comment char or null terminator, stop here
CMP.B #0,D1
beq .done
CMP.B D7,D1
beq .done
ROR.L #8,D7
CMP.B D7,D1
beq .done
ROR.L #8,D7
CMP.B D7,D1
beq .done
ROR.L #8,D7
CMP.B D7,D1
beq .done
ROR.L #8,D7
dontCheckNext:
jsr PrintChar
bra .loop
.done:
rts
TestString:
dc.b "apples ; pears # and bananas",0</syntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Strip(CHAR ARRAY text,chars,result)
BYTE i,j,pos,found
pos=text(0)
FOR i=1 TO text(0)
DO
found=0
FOR j=1 TO chars(0)
DO
IF text(i)=chars(j) THEN
found=1 EXIT
FI
OD
IF found THEN
pos=i-1 EXIT
FI
OD
WHILE pos>0 AND text(pos)='
DO
pos==-1
OD
SCopyS(result,text,1,pos)
RETURN
PROC Test(CHAR ARRAY text,chars)
CHAR ARRAY result(255)
Strip(text,chars,result)
PrintF("""%S"", ""%S"" -> ""%S""%E%E",text,chars,result)
RETURN
PROC Main()
Test("apples, pears # and bananas","#;")
Test("apples, pears ; and bananas","#;")
Test("qwerty # asdfg ; zxcvb","#")
Test("qwerty # asdfg ; zxcvb",";")
Test(" ;this is a comment","#;")
Test("#this is a comment","#;")
Test(" ",";")
Test("","#")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Strip_comments_from_a_string.png Screenshot from Atari 8-bit computer]
<pre>
"apples, pears # and bananas", "#;" -> "apples, pears"
"apples, pears ; and bananas", "#;" -> "apples, pears"
"qwerty # asdfg ; zxcvb", "#" -> "qwerty"
"qwerty # asdfg ; zxcvb", ";" -> "qwerty # asdfg"
" ;this is a comment", "#;" -> ""
"#this is a comment", "#;" -> ""
" ", ";" -> ""
"", "#" -> ""
</pre>
=={{header|Ada}}==
<
procedure Program is
Comment_Characters : String := "#;";
Line 68 ⟶ 193:
end;
end loop;
end Program;</
=={{header|Aime}}==
<
{
b.size(b.look(0, ";#")).bf_drop(" \t").bb_drop(" \t");
Line 83 ⟶ 208:
0;
}</
=={{header|ALGOL 68}}==
Line 89 ⟶ 214:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<
PROC trim comment = (STRING line, CHAR marker)STRING:(
Line 114 ⟶ 239:
grep in string(re marker, line, index, NIL);
print((q, line[:index-1], q, new line))
END CO</
Output:
<pre>
Line 126 ⟶ 251:
=={{header|ALGOL W}}==
Leading and trailing spaces are removed from the result, as per the March 29 2011 task version.
<
% determines the non-comment portion of the string s, startPos and endPos are %
% returned set to the beginning and ending character positions (indexed from 0) %
Line 168 ⟶ 293:
testStripComments( " apples, pears" )
end
end.</
{{out}}
<pre>
Line 178 ⟶ 303:
=={{header|Applesoft BASIC}}==
<
20 S$(1)="APPLES, PEARS # AND BANANAS"
30 S$(2)="APPLES, PEARS ; AND BANANAS"
Line 203 ⟶ 328:
250 IF A$ = " " THEN NEXT I
260 LET S$ = MID$(S$, 1, I)
270 RETURN</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">stripComments: function [str][
strip replace str {/[#;].+/} ""
]
loop ["apples, pears # and bananas", "apples, pears ; and bananas"] 'str [
print [str "->" stripComments str]
]</syntaxhighlight>
{{out}}
<pre>apples, pears # and bananas -> apples, pears
apples, pears ; and bananas -> apples, pears</pre>
=={{header|AutoHotkey}}==
<
str := "apples, pears # and bananas"
str2:= "apples, pears, `; and bananas" ; needed to escape the ; since that is AHK's comment marker
Line 224 ⟶ 364:
}
return String1
}</
Output:
<pre>
Line 233 ⟶ 373:
=={{header|AutoIt}}==
It was always said in discussion, the task is not really stripping comments. It's only a truncation.
<syntaxhighlight lang="autoit">
Dim $Line1 = "apples, pears # and bananas"
Dim $Line2 = "apples, pears ; and bananas"
Line 251 ⟶ 391:
Next
EndFunc ;==>_StripAtMarker
</syntaxhighlight>
Output:
<pre>
Line 265 ⟶ 405:
That means: the comment starts with the first semicolon outside a string.
<syntaxhighlight lang="autoit">
Dim $aLines[4] = _
[ _
Line 322 ⟶ 462:
Next
EndFunc ;==>_LineStripComment
</syntaxhighlight>
Output:
<pre>
Line 348 ⟶ 488:
=={{header|AWK}}==
<
{
sub("[ \t]*[#;].*$","",$0);
print;
}</
=={{header|
==={{header|ANSI BASIC}}===
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">100 DECLARE EXTERNAL FUNCTION FNstripcomment$
110 LET marker$="#;"
120 PRINT """";FNstripcomment$("apples, pears # and bananas", marker$);""""
130 PRINT """";FNstripcomment$("apples, pears ; and bananas", marker$);""""
140 PRINT """";FNstripcomment$(" apples, pears ", marker$);""""
150 END
160 !
170 EXTERNAL FUNCTION
180 FOR I=1 TO LEN(delim$)
190 LET D = POS(text$, delim$(I:I))
200 IF D>0
210 NEXT I
220 LET FNstripcomment$=RTRIM$(text$)
230 END FUNCTION</syntaxhighlight>
Output:
<pre>
"apples, pears"
"apples, pears"
" apples, pears"</pre>
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">arraybase 1
dim s$(4)
s$[1] = "apples, pears # and bananas"
s$[2] = "apples, pears ; and bananas"
s$[3] = "# this is a comment"
s$[4] = " # this is a comment with leading whitespace"
for i = 1 to 4
call stripComment(s$[i], "#;")
print s$[i], " => Length = "; length(s$[i])
next i
end
subroutine stripComment(s$, commentMarkers$)
if s$ = "" then return
i = instr(s$, commentMarkers$)
if i > 0 then
s$ = left$(s$, i - 1)
s$ = trim(s$) # removes both leading and trailing whitespace
end if
end subroutine</syntaxhighlight>
{{out}}
<pre>apples, pears # and bananas => Length = 27
apples, pears ; and bananas => Length = 27
# this is a comment => Length = 19
# this is a comment with leading whitespace => Length = 45</pre>
=={{header|BQN}}==
<code>StripW</code> only removes spaces. <code>StripC</code> uses that in conjunction with a filter that removes comments.
<syntaxhighlight lang="bqn">StripW←((∨`∧∨`⌾⌽)' '⊸≠)⊸/
StripC←StripW (¬·∨`∊⟜"#;")⊸/
•Show StripC " apples, pears # and bananas "
•Show StripC " apples, pears ; and bananas"</syntaxhighlight>
<syntaxhighlight lang="text">"apples, pears"
"apples, pears"</syntaxhighlight>
=={{header|Bracmat}}==
<
oranges, mangos ; and a durian"
: ?text
Line 392 ⟶ 577:
& !newText \n cleanUp$!text:?newText
& out$(str$!newText)
);</
Output:
<pre>
Line 399 ⟶ 584:
=={{header|C}}==
<
int main()
Line 424 ⟶ 609:
return 0;
}</
Output:
<pre>
Line 440 ⟶ 625:
=={{header|C sharp|C#}}==
<
using System.Text.RegularExpressions;
Line 450 ⟶ 635:
return Regex.Replace(str, delimiter + ".+", string.Empty).Trim();
}
</syntaxhighlight>
Sample output:
<pre>
Line 460 ⟶ 645:
=={{header|C++}}==
<
#include <string>
Line 482 ⟶ 667:
}
return 0;
}</
Sample output:
<pre>
Line 492 ⟶ 677:
=={{header|Clojure}}==
<
"apples "</
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<
program-id. StripComments.
Line 517 ⟶ 702:
unstring line-text delimited by "#" or ";" into line-text
display quote, function trim(line-text), quote
.</
{{out}}
<pre>"apples, pears"
Line 523 ⟶ 708:
=={{header|Common Lisp}}==
<
"Truncate s at the first occurrence of a character in cs."
(defun comment-char-p (c)
(some #'(lambda (x) (char= x c)) cs))
(let ((pos (position-if #'comment-char-p s)))
(subseq s 0 pos)))</
{{Out}}
Line 543 ⟶ 728:
=={{header|D}}==
<
string remove1LineComment(in string s, in string pat=";#") {
Line 555 ⟶ 740:
writeln(s, "\n====>\n", s.remove1LineComment());
}</
{{out}}
<pre>apples, pears # and bananas
Line 564 ⟶ 749:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 581 ⟶ 766:
Writeln('apples, pears ; and bananas --> ' + DoStripComments('apples, pears ; and bananas',';'));
Readln;
end.</
=={{header|DWScript}}==
<
begin
var p := FindDelimiter('#;', s);
Line 593 ⟶ 778:
PrintLn(StripComments('apples, pears # and bananas'));
PrintLn(StripComments('apples, pears ; and bananas'));</
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
func$ strip s$ .
i = 1
repeat
c$ = substr s$ i 1
until c$ = "#" or c$ = ";" or c$ = ""
if c$ = " " and sp = 0
sp = i
elif c$ <> " "
sp = 0
.
i += 1
.
if sp = 0
sp = i
.
return substr s$ 1 (sp - 1)
.
print strip "Regular string" & "."
print strip "With a hash# a comment" & "."
print strip "With a hash # a comment" & "."
print strip "With a semicolon ; a comment" & "."
print strip "No comment " & "."
</syntaxhighlight>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( strip_comments_from_string ).
Line 613 ⟶ 825:
not_comment( $; ) -> false;
not_comment( _ ) -> true.
</syntaxhighlight>
{{out}}
<pre>
Line 623 ⟶ 835:
=={{header|F_Sharp|F#}}==
<
s
|> Seq.takeWhile (fun c -> c <> '#' && c <> ';')
|> Seq.map System.Char.ToString
|> Seq.fold (+) ""</
=={{header|Factor}}==
<
: strip-comments ( str -- str' )
[ "#;" member? not ] take-while "" like ;</
=={{header|Fantom}}==
Using a regular expression:
<
{
static Str removeComment (Str str)
Line 654 ⟶ 866:
echo (removeComment ("String with comment ; here"))
}
}</
=={{header|Forth}}==
Line 666 ⟶ 878:
Tested with GForth on Windows
<
: LASTCHAR ( addr len -- addr len c) 2DUP + C@ ;
Line 691 ⟶ 903:
: COMMENT-STRIP ( addr len -- addr 'len) -LEADING -COMMENT -TRAILING ;
</
<pre>S" apples, pears # and bananas" COMMENT-STRIP TYPE apples, pears ok
S" apples, pears ; and bananas" COMMENT-STRIP TYPE apples, pears ok</pre>
=={{header|Fortran}}==
<
module string_routines
!****************************************************
Line 739 ⟶ 951:
!****************************************************
end program main
!****************************************************</
output:
<pre>
Line 747 ⟶ 959:
=={{header|FreeBASIC}}==
<
Sub stripComment(s As String, commentMarkers As String)
Line 773 ⟶ 985:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 782 ⟶ 994:
=> Length = 0
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasid">
include "NSLog.incl"
local fn StripCommentsFromString( string as CFStringRef ) as CFStringRef
CFRange range = fn StringRangeOfCharacterFromSet( string, fn CharacterSetWithCharactersInString( @"#;" ) )
if ( range.location != NSNotFound )
string = fn StringSubstringToIndex( string, range.location )
string = fn StringByTrimmingCharactersInSet( string, fn CharacterSetWhitespaceSet )
end if
end fn = string
NSLog(@"%@",fn StripCommentsFromString(@"apples, pears # and bananas"))
NSLog(@"%@",fn StripCommentsFromString(@"apples, pears ; and bananas"))
HandleEvents
</syntaxhighlight>
=={{header|Go}}==
<
import (
Line 810 ⟶ 1,040:
fmt.Printf("stripped: %q\n", stripComment(s))
}
}</
Output:
<pre>
Line 822 ⟶ 1,052:
=={{header|Groovy}}==
<
Testing:
<
assert 'apples, pears' == stripComments('apples, pears ; and bananas')</
=={{header|Haskell}}==
<
main = getContents >>=
mapM_ (putStrLn . takeWhile (`notElem` ms)) . lines</
=={{header|Icon}} and {{header|Unicon}}==
<
# return part of string up to first character in 'markers',
# or else the whole string if no comment marker is present
Line 845 ⟶ 1,075:
write (strip_comments ("apples, pears # and bananas", cset ("#;")))
write (strip_comments ("apples, pears ; and bananas", cset ("#;")))
end</
Output:
Line 855 ⟶ 1,085:
=={{header|Inform 7}}==
<
When play begins:
Line 865 ⟶ 1,095:
say "[T] -> ";
replace the regular expression "<#;>.*$" in T with "";
say "[T][line break]".</
Since square brackets have a special meaning in strings, Inform's regular expression syntax uses angle brackets for character grouping.
=={{header|J}}==
'''Solution 1''' (mask & filter): <
'''Solution 2''' (index & cut): <
'''Example''':<
"apples, pears"
strip ' apples, pears ; and bananas'
=={{header|Java}}==
<
public class StripLineComments{
Line 901 ⟶ 1,131:
}
}
}</
=={{header|JavaScript}}==
===ES5===
<
var re1 = /^\s+|\s+$/g; // Strip leading and trailing spaces
var re2 = /\s*[#;].+$/g; // Strip everything after # or ; to the end of the line, including preceding spaces
Line 916 ⟶ 1,146:
alert(stripComments(s1) + '\n' + stripComments(s2));
</syntaxhighlight>
A more efficient version that caches the regular expressions in a closure:
<
var re1 = /^\s+|\s+$/g;
var re2 = /\s*[#;].+$/g;
Line 927 ⟶ 1,157:
};
}());
</syntaxhighlight>
A difference with the two versions is that in the first, all declarations are processed before code is executed so the function declaration can be after the code that calls it. However in the second example, the expression creating the function must be executed before the function is available, so it must be before the code that calls it.
===ES6===
<
'use strict';
Line 992 ⟶ 1,222:
// MAIN ---
return main();
})();</
{{Out}}
<pre>apples, pears
Line 999 ⟶ 1,229:
=={{header|jq}}==
If your version of jq has regex support, the task can be accomplished with the following one-liner:
<
Otherwise, we can define strip_comment as a jq filter, as follows. For clarity, the helper functions are presented as top-level functions.
<
def is_whitespace: . as $in | " \n\r\f\t" | index($in);
Line 1,022 ⟶ 1,252:
end ) as $ix
| if $ix then .[0:$ix] else . end
| trim;</
'''Example''':
<
{{out}}
<
=={{header|Julia}}==
<tt>striplinecomment</tt> is designed to be flexible and robust. By default <tt>#</tt> and <tt>;</tt> are considered comment defining characters, but any characters can be used by passing them as the string <tt>cchars</tt>. All such characters are escaped in the regular expression used to eliminate comments to allow characters special to the Regex language (e.g. <tt>^</tt>, <tt>$</tt>, <tt>[</tt>) to be used as a comment character.
<syntaxhighlight lang="julia">
using Printf
Line 1,055 ⟶ 1,285:
println(" \"", s, "\"")
end
</syntaxhighlight>
{{out}}
Line 1,079 ⟶ 1,309:
It then removes whitespace from the beginning and end of the resulting string:
<
val r = Regex("""(/\*.*\*/|//.*$)""")
Line 1,093 ⟶ 1,323:
)
for (string in strings) println(stripComments(string))
}</
{{out}}
Line 1,104 ⟶ 1,334:
=={{header|Liberty BASIC}}==
<
string2$ = "pears;, " + chr$(34) + "apples ; " + chr$(34) + " an;d bananas"
commentMarker$ = "; #"
Line 1,119 ⟶ 1,349:
next i
parse$ = Left$(string$, (i - 1))
End Function</
=={{header|Lua}}==
<
s1 = "apples, pears # and bananas"
Line 1,128 ⟶ 1,358:
print ( string.match( s1, "[^"..comment_symbols.."]+" ) )
print ( string.match( s2, "[^"..comment_symbols.."]+" ) )</
=={{header|Maple}}==
<
["apples, pears", "apples, pears"]</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
apples, pears ; and bananas";
b = StringReplace[a, RegularExpression["[ ]+[#;].+[\n]"] -> "\n"];
StringReplace[b, RegularExpression["[ ]+[#;].+$"] -> ""] // FullForm</
{{out}}
<pre>"apples, pears\napples, pears"</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<
e = min([find(line=='#',1),find(line==';',1)]);
if ~isempty(e)
Line 1,151 ⟶ 1,381:
end;
end;
</syntaxhighlight>
Output:
<pre>>> stripcomment('apples, pears # and bananas\n')
Line 1,159 ⟶ 1,389:
=={{header|MiniScript}}==
<
comment = test.indexOf("#")
if comment == null then comment = test.indexOf(";")
Line 1,172 ⟶ 1,402:
print strip("This is a semicolon test ; a comment") + "."
print strip("This is a no comment test ") + "."
</syntaxhighlight>
{{out}}
<pre>
Line 1,181 ⟶ 1,411:
=={{header|Nim}}==
<
proc removeComments(line: string; sep: char): string =
Line 1,193 ⟶ 1,423:
echo "Stripped: “$#”" % Str1.removeComments('#')
echo "Original: “$#”" % Str2
echo "Stripped: “$#”" % Str2.removeComments(';')</
{{out}}
Line 1,202 ⟶ 1,432:
=={{header|Objeck}}==
<
class StripComments {
Line 1,230 ⟶ 1,460:
};
}
}</
=={{header|OCaml}}==
<
let len = String.length str in
let rec aux print i =
Line 1,252 ⟶ 1,482:
strip_comments "apples, pears # and bananas\n";
strip_comments "apples, pears ; and bananas\n";
;;</
or with an imperative style:
<
let print = ref true in
String.iter (function
| ';' | '#' -> print := false
| '\n' -> print_char '\n'; print := true
| c -> if !print then print_char c)</
=={{header|Oforth}}==
<
| firstMarker |
markers map(#[ s indexOf ]) reduce(#min) ->firstMarker
s firstMarker ifNotNull: [ left(firstMarker 1 - ) ] strip ;</
{{out}}
Line 1,283 ⟶ 1,513:
=={{header|Perl}}==
<
{
s/[#;].*$//s; # remove comment
Line 1,289 ⟶ 1,519:
s/\s+$//; # remove trailing whitespace
print
}</
=={{header|Phix}}==
Added a couple of things that can go wrong with something nowhere near sufficiently smart or for that matter language-specific enough.<br>
A line comment inside a block comment (eg " /* left -- right */") could also be very dodgy, and perhaps vice versa.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">comments</span><span style="color: #0000FF;">={</span><span style="color: #008000;">"#"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">";"</span><span style="color: #0000FF;">})</span>
<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;">comments</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<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;">comments</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</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>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim_tail</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"apples, pears # and bananas"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"apples, pears ; and bananas"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"apples, pears and bananas "</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" WS_CAPTION = #00C00000, -- = WS_BORDER+WS_DLGFRAME"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" WS_CAPTION = #00C00000, -- = WS_BORDER+WS_DLGFRAME"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"--"</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">strip_comments</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" title = \"--Title--\""</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"--"</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,322 ⟶ 1,555:
=={{header|PicoLisp}}==
<
(prinl (car (split (chop Str) "#" ";"))) )</
Output:
<pre>
Line 1,331 ⟶ 1,564:
=={{header|PL/I}}==
<
if k = 0 then put skip list (text);
else put skip list (substr(text, 1, k-1));</
=={{header|Prolog}}==
{{works with|SWI Prolog}}
This version is implemented as a state automata to strip multiple lines of comments.
<
stripcomment([A|AL],[A|BL],a) :- \+ A=0';, \+ A=0'# , \+ A=10, \+ A=13 , stripcomment(AL,BL,a).
stripcomment([A|AL], BL ,a) :- ( A=0';; A=0'#), \+ A=10, \+ A=13 , stripcomment(AL,BL,b).
Line 1,348 ⟶ 1,581:
apples, pears # and bananas",
stripcomment(In,Out),
format("~s~n",[Out]).</
Output:
<pre>
Line 1,356 ⟶ 1,589:
</pre>
This version uses prolog's pattern matching with two append/3 to strip 1 line.
<
At the query console:
<pre>
Line 1,368 ⟶ 1,601:
=={{header|PureBasic}}==
<
Protected result$=Str$, l, l1, l2
l1 =FindString(Str$,"#",1)
Line 1,384 ⟶ 1,617:
EndIf
ProcedureReturn result$
EndProcedure</
Implementation
<
#instring2 ="apples, pears ; and bananas"
PrintN(Strip_comments(#instring1))
PrintN(Strip_comments(#instring2))</
Output:<pre>
apples, pears
Line 1,398 ⟶ 1,631:
=={{header|Python}}==
===Procedural===
<
for s in sep:
i = line.find(s)
Line 1,408 ⟶ 1,641:
print remove_comments('apples ; pears # and bananas', ';#')
print remove_comments('apples ; pears # and bananas', '!')
</syntaxhighlight>
===Regular expressions===
You could also use a regular expression
<
m = re.match(r'^([^#]*)#(.*)$', line)
if m: # The line contains a hash / comment
line = m.group(1)
</syntaxhighlight>
===Functional===
Line 1,424 ⟶ 1,657:
which is defined over strings as well as lists.
{{Works with|Python|3.7}}
<
from itertools import takewhile
Line 1,452 ⟶ 1,685:
'''
)
)</
{{Out}}
<pre>apples, pears
apples, pears</pre>
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">SUB stripComment (s$, commentMarkers$)
IF s$ = "" THEN RETURN
i = INSTR(s$, commentMarkers$)
IF i > 0 THEN
s$ = LEFT$(s$, i - 1)
s$ = LTRIM$((RTRIM$(s$))) '' removes both leading and trailing whitespace
END IF
END SUB
DIM s$(1 TO 4)
s$(1) = "apples, pears # and bananas"
s$(2) = "apples, pears ; and bananas"
s$(3) = "# this is a comment"
s$(4) = " # this is a comment with leading whitespace"
FOR i = 1 TO 4
CALL stripComment(s$(i), "#;")
PRINT s$(i), " => Length ="; LEN(s$(i))
NEXT i</syntaxhighlight>
{{out}}
<pre>apples, pears # and bananas => Length = 27
apples, pears ; and bananas => Length = 27
# this is a comment => Length = 19
# this is a comment with leading whitespace => Length = 45</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="Quackery"> [ char ; over find split drop
char # over find split drop ] is strip ( $ --> $ )
( or, to pander to the debacle by trimming trailing whitespace:
[ char ; over find split drop
char # over find split drop
reverse trim reverse ] is strip ( $ --> $ )
( or, to pander to the debacle by trimming leading and trailing whitespace:
[ char ; over find split drop
char # over find split drop
trim reverse trim reverse ] is strip ( $ --> $ )
$ "apples, pears # and bananas" strip echo$ cr
$ "apples, pears ; and bananas" strip echo$ cr
</syntaxhighlight>
{{out}}
<pre>apples, pears
apples, pears
</pre>
=={{header|R}}==
This is most cleanly accomplished using the <code>stringr</code> package.
<
{
if(!require(stringr)) stop("you need to install the stringr package")
str_trim(str_split_fixed(str, "#|;", 2)[, 1])
}</
Example usage:
<
"apples, pears # and bananas", # the requested hash test
"apples, pears ; and bananas", # the requested semicolon test
Line 1,474 ⟶ 1,763:
" apples, pears # and bananas" # with preceding spaces
)
strip_comments(x)</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang at-exp racket
Line 1,499 ⟶ 1,788:
(strip-comments2 text) ; -> "apples, pears\napples, pears"
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
=={{header|Red}}==
Red has an embedded parse engine called Parse.
For more info on the Parse dialect. http://www.red-lang.org/2013/11/041-introducing-parse.html.
<syntaxhighlight lang="red">
>> parse s: "apples, pears ; and bananas" [to [any space ";"] remove thru end]
== true
>> s
== "apples, pears"
</syntaxhighlight>
But you can also use simple series operations to find where something occurs, clear from that position, and trim leading and trailing spaces.
<syntaxhighlight lang="red">
s: "apples, pears ; and bananas"
dlms: charset "#;"
Line 1,527 ⟶ 1,816:
trim head clear find s dlms
== "apples, pears"
</syntaxhighlight>
=={{header|REXX}}==
Line 1,538 ⟶ 1,827:
<br>The fourth subroutine is similar to the third version but more idiomatic.
<br><br>All four subroutines trim leading ''and'' trailing blanks after stripping the "comments".
<
old1= ' apples, pears # and bananas' ; say ' old ───►'old1"◄───"
new1= stripCom1(old1) ; say ' 1st version new ───►'new1"◄───"
Line 1,578 ⟶ 1,867:
if p\==0 then x=left(x,p-1) /*shorten the X string by one character*/
end /*k*/ /* [↑] If p==0, then char wasn't found*/
return strip(x) /*return the stripped shortened string.*/</
'''output'''
<pre>
Line 1,595 ⟶ 1,884:
===version 2===
<
Call stripd ' apples, pears and bananas'
Exit
Line 1,608 ⟶ 1,897:
Say '>'old'<'
Say '>'new'<'
Return</
=={{header|Ring}}==
<
aList = 'apples, pears # and bananas'
see aList + nl
Line 1,625 ⟶ 1,914:
if nr > 0 cList = substr(bList,1,nr-1) ok
return cList
</syntaxhighlight>
=={{header|RPL}}==
In addition to the input string, a second argument defines if whitespaces must be removed (mode=1) or not (mode=0).
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪
'''IF''' DUP 1 1 SUB " " == '''THEN'''
2 OVER SIZE SUB '''TRIMF END'''
'''IF''' DUP DUP SIZE DUP SUB " " == '''THEN'''
1 OVER SIZE 1 - SUB '''TRIMF END'''
≫ ‘'''TRIMF'''’ STO
≪ → string charset
≪ 0 1 charset SIZE '''FOR''' j
'''IF''' string charset j DUP SUB POS
'''THEN''' LAST SWAP DROP charset SIZE 'j' STO '''END'''
'''NEXT'''
≫ ≫ ''''STPOS'''' STO
≪ SWAP
'''IF''' DUP "#;" '''STPOS THEN'''
1 LAST 1 - SUB '''IF''' SWAP '''THEN TRIMF END'''
'''ELSE''' SWAP DROP '''END'''
≫ ''''NOCOM'''' STO
|
'''TRIMF''' ''( "string" -- "trimmed" ) ''
if flag 1 set and 1st char of string is a space
then recursively process tail(string)
if flag 1 set and last char of string is a space
then recursively process head(string)
'''STPOS''' ''( "string" "char_set" -- position ) ''
position = 0, for each character in set
if char in string
update position, request loop exit
'''NOCOM''' ''( "string" mode -- "no_comment" )''
if there is a comment
remove it from string, and spaces too if required
otherwise clean stack
|}
{{in}}
<pre>
" apple, pears # and bananas" 0 NOCOM
" apple, pears # and bananas" 1 NOCOM
" apple, pears ; and bananas" 1 NOCOM
</pre>
{{out}}
<pre>
3: " apple, pears "
2: "apple, pears"
1: "apple, pears"
</pre>
=={{header|Ruby}}==
<
def strip_comment( markers = ['#',';'] )
re = Regexp.union( markers ) # construct a regular expression which will match any of the markers
Line 1,646 ⟶ 1,996:
p str.strip_comment('and')
p " \t \n ;".strip_comment
p "".strip_comment</
{{out}}
<pre>
Line 1,658 ⟶ 2,008:
=={{header|Rust}}==
<
input
.find(markers)
Line 1,670 ⟶ 2,020:
println!("{:?}", strip_comment("apples, pears ; and bananas", &['#', ';']));
println!("{:?}", strip_comment("apples, pears and bananas ", &['#', ';']));
}</
{{out}}
<pre>
Line 1,679 ⟶ 2,029:
=={{header|Scala}}==
<
def stripComments1(s:String, markers:String =";#")=s takeWhile (!markers.contains(_)) trim
Line 1,701 ⟶ 2,051:
print("apples, pears ; and bananas")
}
}</
Output:
<pre>'apples, pears # and bananas' =>
Line 1,712 ⟶ 2,062:
=={{header|Scheme}}==
{{works with|Guile}}
<
(define (strip-comments s)
Line 1,719 ⟶ 2,069:
(display (strip-comments "apples, pears # and bananas"))(newline)
(display (strip-comments "apples, pears ; and bananas"))(newline)</
Output:<pre>apples, pears
apples, pears</pre>
=={{header|sed}}==
<
# Strip comments
echo "$1" | sed 's/ *[#;].*$//g' | sed 's/^ *//'</
=={{header|Seed7}}==
<
const func string: stripComment (in string: line) is func
Line 1,759 ⟶ 2,109:
writeln(stripComment(line));
end for;
end func;</
Output:
Line 1,771 ⟶ 2,121:
=={{header|Sidef}}==
<
(s - %r'[#;].*').strip;
}
Line 1,779 ⟶ 2,129:
" apples, pears "].each { |s|
say strip_comment(s).dump;
};</
{{out}}
<pre>
Line 1,786 ⟶ 2,136:
"apples, pears"
</pre>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "stripcomment" )
@( description, "The task is to remove text that follow any of a set of" )
@( description, "comment markers, (in these examples either a hash or a" )
@( description, "semicolon) from a string or input line." )
@( see_also, "http://rosettacode.org/wiki/Strip_comments_from_a_string" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure stripcomment is
line : constant string := get_line;
eol : natural := 0;
ch : character;
begin
for i in 1..strings.length( line ) loop
ch := strings.element( line, i );
exit when ch = '#' or ch = ';';
eol := i;
end loop;
if eol > 0 then
? strings.trim( strings.slice( line, 1, eol ), trim_end.both );
end if;
end stripcomment;</syntaxhighlight>
=={{header|Standard ML}}==
Strips comments and trailing spaces.
<
let
val notMarker = fn #"#" => false | #";" => false | _ => true
Line 1,795 ⟶ 2,173:
in
string o dropr Char.isSpace o takel notMarker o full
end</
=={{header|Tcl}}==
<
# Switch the RE engine into line-respecting mode instead of the default whole-string mode
regsub -all -line "\[$commentChars\].*$" $inputString "" commentStripped
# Now strip the whitespace
regsub -all -line {^[ \t\r]*(.*\S)?[ \t\r]*$} $commentStripped {\1}
}</
Demonstration:
<
set input "apples, pears # and bananas
apples, pears ; and bananas"
# Do the stripping
puts [stripLineComments $input]</
Output:
<pre>
Line 1,816 ⟶ 2,194:
</pre>
The above code has one issue though; it's notion of a set of characters is very much that of the RE engine. That's possibly desirable, but to handle ''any'' sequence of characters as a set of separators requires a bit more cleverness.
<
# Convert the character set into a transformation
foreach c [split $commentChars ""] {lappend map $c "\uFFFF"}; # *very* rare character!
Line 1,823 ⟶ 2,201:
# Now strip the whitespace
regsub -all -line {^[ \t\r]*(.*\S)?[ \t\r]*$} $commentStripped {\1}
}</
Output in the example is the same as above.
=={{header|TUSCRIPT}}==
<
strngcomment=*
DATA apples, pears # and bananas
Line 1,837 ⟶ 2,215:
x=SPLIT (s,comment_char,string,comment)
PRINT string
ENDLOOP</
Output:
<pre>
Line 1,848 ⟶ 2,226:
{{works with|pdksh}}
Adapted from the Advanced Bash-Scripting Guide, section 10.1 [http://tldp.org/LDP/abs/html/string-manipulation.html Manipulating Strings].
<
bash$ b='apples, pears # and bananas'
bash$ echo ${a%%;*}
Line 1,854 ⟶ 2,232:
bash$ echo ${b%%#*}
apples, pears
bash$</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function strip_comments(s,char)
If InStr(1,s,char) > 0 Then
Line 1,869 ⟶ 2,247:
WScript.StdOut.WriteLine strip_comments("apples, pears # and bananas","#")
WScript.StdOut.WriteLine strip_comments("apples, pears ; and bananas",";")
</syntaxhighlight>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">const comment_chars = "#;"
fn main() {
s := [
"apples, pears # and bananas",
"apples, pears ; and bananas",
"no bananas"
]
for element in s {
println('source: $element')
println('stripped: ' + strip_comment(element))
}
}
fn strip_comment(source string) string {
if source.index_any(comment_chars) >= 0 {
return source.substr(0, source.index_any(comment_chars))
}
return source
}</syntaxhighlight>
{{out}}
<pre>
source: apples, pears # and bananas
stripped: apples, pears
source: apples, pears ; and bananas
stripped: apples, pears
source: no bananas
stripped: no bananas
</pre>
=={{header|Wren}}==
This is based on what the post 29th March, 2011 requirements appear to be.
<
var stripComments = Fn.new { |s|
Line 1,892 ⟶ 2,302:
var t = stripComments.call(s)
System.print("'%(s)' -> '%(t)'")
}</
{{out}}
Line 1,899 ⟶ 2,309:
' apples, pears ; and bananas' -> 'apples, pears'
' apples, pears ' -> 'apples, pears'
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">string 0; \use zero-terminated strings
func StripComment(Str); \Remove characters after marker and remove
char Str; int I; \ whitespace at beginning and end of string
[I:= 0;
loop case Str(I) of
^#, ^;, 0: quit
other I:= I+1;
while I>0 and Str(I-1)<=$20 do I:= I-1;
Str(I):= 0;
while Str(0)<=$20 do Str:= Str+1;
return Str;
];
int Strings, I;
[Strings:= [
" apples, pears # and bananas",
" apples, pears ; and bananas ",
" apples, pears "];
for I:= 0 to 3-1 do
[ChOut(0, ^");
Text(0, StripComment(Strings(I)));
ChOut(0, ^");
CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
"apples, pears"
"apples, pears"
"apples, pears"
</pre>
=={{header|XProfan}}==
Delimiter in string "#" or ";" will be ignored. Good for INI files.
<
Proc Min
Declare int PC, i, float e, t
Line 1,989 ⟶ 2,433:
waitkey
end</
Output:
<pre>
Line 1,999 ⟶ 2,443:
=={{header|zkl}}==
<
if (Void!=(n:=text.find(c))) text=text[0,n];
text.strip() // remove leading and trailing white space
Line 2,006 ⟶ 2,450:
foreach c in (vm.arglist[1,*]){ text=strip(text,c) }
text
}</
Or, if you want the all-in-one stripper:
<
vm.arglist[1,*].reduce('wrap(text,c){
if (Void!=(n:=text.find(c))) text[0,n] else text
},text)
.strip()
}</
<
String(">", stripper(" apples, pears ; and # bananas","#",";"), "<").println();</
{{out}}
<pre>
|