g | x | w | all
Bytes Lang Time Link
003Uiua231019T175019Zchunes
079Racket230722T173414ZEd The &
002Thunno 2230722T164810ZThe Thon
045C clang m32220807T182230Zc--
038Arturo230115T033620Zchunes
026POSIX Shell + Utilities221226T014953Zнабиячлэ
002Japt221224T154358Znoodle m
006sh + coreutils220807T180222Zmatteo_c
024awk 24bytes solution — it's not all that short but it gets the job done*221225T091706ZRARE Kpo
nan221224T173614Zbigyihsu
055Dart 2.18.4220808T110238ZAlex Rin
034brev220821T203721ZSandra
008Scala220814T090729Zcorvus_1
029Ruby220813T144025ZPascal H
028Python220807T165818Z97.100.9
022Raku220812T172101ZSean
015GolfScript220812T135800ZSamuel W
048Red220812T103752Zchunes
020Regex ECMAScript or better220807T185548ZDeadcode
005Pip220809T153112ZDLosc
005Charcoal220808T113157ZNeil
003BQN220808T215456ZDominic
024Nibbles220809T090814ZDominic
005Haskell + hgl220809T081953ZWheat Wi
010CJam220808T225102ZLuis Men
004K ngn/k220808T223332ZTraws
044JavaScript Node.js220808T122235Znoodle m
021Haskell220807T210313Zc--
033C#220808T143558ZAcer
025MATLAB220808T123250Zrobbie c
002Burlesque220808T103021ZDeathInc
00105AB1E220808T085032ZKevin Cr
041JavaScript Node.js220808T012902ZMatthew
020Rust220808T003913ZBubbler
027PARI/GP220808T000240Zalephalp
016Wolfram Language Mathematica220807T224504Zatt
006Factor220807T223251Zchunes
004Brachylog220807T222702ZUnrelate
063Knight220807T214811ZnaffetS
016Haskell220807T212945ZnaffetS
003Vyxal r220807T194740ZnaffetS
015R220807T192336Zpajonk
070Rust220807T182646Zmousetai
020Haskell220807T180000Zmatteo_c
054J220807T172608ZJonah
001Jelly220807T174843ZJonathan
001Dyalog APL220807T174246Zrabbitgr

Uiua, 3 bytes

▽∊,

Try it!

▽∊,
  ,  # over
 ∊   # member
▽    # keep

Racket, 79 bytes

(define(p s a)(apply string(for/list([c s]#:when(string-contains? a(~a c)))c)))

Try it online!


Explanation

We create a function called p that receives two inputs s and a which are the string to match and the string of what to match respectively. We loop through the characters of s and see whether each character appears in a. When a character does appear, we accumulate that character into a list. Once the list is obtained, we convert the characters to a single string.

(define (projection s a)
  (apply string
    (for/list ([char s] #:when (string-contains? a (~a char)))
      char)))

Conclusion

Have an amazing weekend!

Thunno 2, 2 bytes

Ƈị

Try it online!

I/O as a list of characters.

Explanation

    # Implicit input
 ị  # Keep only the characters of the first input
Ƈ   # which are contained in the second input
    # Implicit output

C (clang) -m32, 54 53 45 bytes

-1 byte thanks to @ceilingcat
-8 bytes thanks to @jdt

f(*s,a){for(;*s;)write(1,s,!!index(a,*s++));}

Try it online!

Explanation

f(*s,a){      // function f() takes a wide-character string (s) and an int (a)
 for(;*s;)    // while we're not at the end of the string
  write(1,s,N // write N bytes from s to stdout
   !!<expr>   // if <expr> is NULL, return 0, otherwise 1
    index(a,c // if the character `c` is found in `(const char *) a`,
              //   return a pointer to it's occurrence, otherwise `NULL`
     *s++     // return the current character and increment s
    )         // end call to index(3)
  );          // end call to write(2)
}             // end function f()

Caveat

There is undefined behavior in the form of an unsequenced modification and access to s, but clang happened to evaluate s (the second parameter to write) before incrementing it in the call to index(3) so in this case it works.

Arturo, 38 bytes

$[s,a]->join select split s'c[in? c a]

Try it

POSIX Shell + Utilities, 26 bytes

printf %s "$1"|tr -cd "$2"

Fundamentally, the operation is tr -cd alphabet, all of 11 bytes on the right side of the pipe; more than half of the space is spent on turning the specified calling convention into data in a file. Unclear if taking the input from the standard input stream is allowed.

The tr alphabet accepts \n and \t for line and tab, but the spec does comment that it means a literal one, I think? Either work, but.

Transcript of test cases:

$ cat c.sh; echo; wc -c c.sh
printf %s "$1"|tr -cd "$2"
26 c.sh
$ ./c.sh "abcd" "12da34"; echo
ad
$ ./c.sh "hello, world!" "aeiou"; echo
eoo
$ ./c.sh "hello, world!" "abcdefghijklmnopqrstuvwxyz"; echo
helloworld
$ ./c.sh "Hello, World!" "abcdefghijklmnopqrstuvwxyz"; echo
elloorld
$ ./c.sh "Hello, World!" "abcdef"; echo
ed
$ ./c.sh "Hello, World!" "!,.
        "; echo
, !
$ ./c.sh "172843905" "abc123"; echo
123
$ ./c.sh "fizzbuzz" ""; echo

$ ./c.sh "fizzbuzz" "fizzbuzz"; echo
fizzbuzz
$ ./c.sh "" "fizzbuzz"; echo

$ ./c.sh "fizzbuzz" "zzzzz"; echo
zzzz
$ ./c.sh "" ""
```

Japt, 3 2 bytes

fV

Try it

Takes input strings as character arrays

3 bytes w/ strings for input:

oV1

Try it

oV1
o     : only keep characters in first input and
 V    : second input
  1   : case sensitive

sh + coreutils, 6 bytes

tr -cd

Takes string s from stdin, alphabet a as an argument.

awk 24-bytes solution — it's not all that short but it gets the job done*

— *some bugs still exist

echo 'abcd 12da34' | 
awk 'gsub("[^"$NF"]",_,$--NF)'  
ad

echo 'hello, world!=naeiou' | 
awk 'gsub("[^"$NF"]",_,$--NF)' FS== | 
awk NF=NF FS= OFS='\n' | awk '!__[$_]++' ORS= 
awk 'gsub("[^"$!_ "]",_,$NF)
     gsub("[^"$NF"]",_,$!_)($_=$NF)' FS==
eo

Go, 104 bytes

import."strings"
func f(s,a string)(o string){for i:=range s{r:=s[i:i+1]
if Contains(a,r){o+=r}}
return}

Attempt This Online!

Dart (2.18.4), 55 bytes

f(s,a)=>s.split('').where((e)=>!!a.contains(e)).join();

brev, 34 bytes

(as-list(c lset-intersection eq?))

Brev imports all of srfi-1 by default. The partial application combinator c applies eq? and then the as-list combinator makes the list operator work on (and return) strings (and other stuff) as if they were lists.

Scala, 8 bytes

_.filter

Try it online!

This is an expression of type String => Set[Char] => String. It uses the fact that a Set[T] is a function T => Boolean, which is used the predicate here.

Ruby, 29 bytes

->s,a{s.gsub(/./){a[_1]&&_1}}

Previous version which had flaws indicated by Deadcode:

->s,a{s.tr(s.tr(a,""),"")}

Try it online!

Python, 35 28 bytes

lambda a,b:filter(b.count,a)

Attempt This Online!

Takes in either strings or lists of characters, outputs a list of characters.


-7 bytes from @dingledooper by using filter + count instead of list comprehension and in

Raku, 22 bytes

{$^a.trans($^b=>""):c}

Try it online!

trans is Raku's beefed-up version of Perl 5's transliteration operator tr.

GolfScript, 15 bytes

~`{1$?)\''if}+%

Try it online!

Red, 48 bytes

func[a b][foreach x a[if find/case b x[prin x]]]

Try it online!

Regex (ECMAScript or better), 20 bytes

s/(.)(?!.*␀.*\1)//sg

Try it online! - ECMAScript 2018
Try it online! - Perl
Try it online! - PCRE2
Try it online! - Boost
Try it online! - Python
Try it online! - Ruby
Try it online! - .NET

This is a single regex substitution, to be applied once. Input is taken in the form of the two strings delimited by NUL (ASCII 0).

Above and below, represents what is actually a raw NUL character in the regex.

s/              # Begin substitution - match the following:
      (.)       # \1 = one character
      (?!       # Negative lookahead - match if the following can't match:
          .*    # Skip over as many characters as possible, minimum zero, to make
                # the following match:
          ␀     # Skip over the NUL delimiter
          .*    # Skip over as many characters as possible, minimum zero, to make
                # the following match:
          \1    # Match the character we captured in \1
      )
/               # Substitution - replace with the following:
                # Empty string
/               # Flags:
s               # single line - "." will match anything, including newline
g               # global - find and replace all matches, going from left to right

This automatically erases the NUL and everything following it, because NUL and all characters following it are themselves not followed by NUL, so the negative lookahead matches for each of them.

(More test harnesses to come.)

As far as ECMAScript goes, this requires ECMAScript 2018 (aka ES9) due to the use of the s flag.

In Ruby, the m flag is used, which is the Ruby equivalent of what is s in most other regex engines.

\$\large\textit{Anonymous functions}\$

Perl, 42 bytes

sub{$_=join'␀',@_;s/(.)(?!.*␀.*\1)//sg;$_}

Try it online!

Takes the two strings as arguments.

Beaten by a 35 byte solution based on an unposted solution by Sisyphus: Try it online!

Ruby, 42 41 bytes

-1 byte thanks to Steffan

->s,a{(s+?␀+a).gsub /(.)(?!.*␀.*\1)/m,''}

Try it online!

PowerShell, 42 bytes

$args-join'␀'-creplace'(?s)(.)(?!.*␀.*\1)'

Try it online!

Takes the two strings as arguments.

JavaScript (ES9), 43 bytes

a=>a.join`␀`.replace(/(.)(?!.*␀.*\1)/sg,'')

Try it online!

Takes a list containing the two strings.

Java, 52 bytes

s->a->(s+"␀"+a).replaceAll("(?s)(.)(?!.*␀.*\\1)","")

Attempt This Online!

\$\large\textit{Full programs}\$

Perl, 37 bytes

$_=join'',<>;s/(.)(?!.*␀.*\1)//sg;say

Try it online!

Takes multiline input (terminated by EOF) using NUL as a delimiter between the two strings.

Beaten by a 19 byte solution based on an unposted solution by Sisyphus: Try it online! (they should really post it), or 25 bytes to insert chomp; at the beginning if being picky about the output being followed by a NUL.

Pip, 5 bytes

a@X^b

Try It Online!

Explanation

    b  Second command-line argument
   ^   Split into characters
  X    Convert to regex that matches any of those characters
 @     Find all matches of the regex in
a      First command-line argument

By default, the list of matches is concatenated together and output.

Charcoal, 5 bytes

Φθ№ηι

Try it online! Link is to verbose version of code. Explanation: Trivial port of @dingledooper's golf to adam's Python answer.

 θ      First input
Φ       Filtered where
  №     Count of
    ι   Current character
   η    In second input
        Implicitly print

Newlines and other unprintables need to be entered using JSON format.

BQN, 3 bytes

∊/⊣

Try it at BQN REPL

 /      # Replicate elements of 
  ⊣     # left argument
        # by
∊       # 1 if each element of left argument is in right argument
        # 0 otherwise

Nibbles, 2 bytes (4 nibbles)

|@?@
|       # filter
 @      # the (second) input array
        # for truthy results of the function:
  ?     # index (or 0 if not found) 
   @    # in the (first) input array

enter image description here

Haskell + hgl, 5 bytes

fl<fe

Attempt This Online!

Pretty straight forward. fl filters fe checks if something is an element. Ends up being the same as the vanilla Haskell answer.

Reflection

This is a very simple task so there's not a lot to be said but:

CJam, 10 bytes

Loosely inspired by this answer to another challenge.

l~:A;{A&}/

Input is a line containing the two strings separated by a space. If a string contains special characters it needs to be defined explicitly as an array of chars.

Try it online! Or verify all test cases.

How it works

l~          e# Read line and evaluate: pushes the two strings onto the stack
  :A;       e# Copy the second string into variable A, then pop
     {  }/  e# For each character in the first string, do the following
            e# Implicitly push current character of the first string
      A     e# Push the second string
       &    e# Set intersection. This gives the current char or an empty string
            e# Implicitly display stack contents

K (ngn/k), 4 bytes

Uses set difference (^) to compute the intersection: x∩y = x-(x-y)

^/^\

Try it online!

JavaScript (Node.js), 44 bytes

s=>a=>[...s].filter(c=>a.includes(c)).join``

Try it online!

Unfortunately, using .filter(a.includes) for 38 (wow!) throws String.prototype.includes called on null or undefined

Haskell, 21 bytes

s#a=[c|c<-s,elem c a]

Try it online!

C#, 33 bytes

(s,t)=>s.Where(c=>t.Contains(c));

Try it online!

MATLAB, 25 bytes

f=@(a,b)a(ismember(a,b))

Technically, only the call of a(ismember(a,b)) is required to fulfill the task, but to make it a callable function a function handle is created. Also, the inputs have to be of type char, not string, as a char is an array whereas a string is more like a complete unit in MATLAB.

Try it online!

Burlesque, 2 bytes

IN

Try it online!

Builtin intersection.

05AB1E, 1 byte

Ã

Another 1-byte builtin. Takes the inputs in the order alphabet,string.

Try it online or verify all test cases.

JavaScript (Node.js), 41 bytes

Presently invalid as does not handle alphabets containing - or ]. (as pointed out by Deadcode)

s=>a=>s.replace(RegExp(`[^${a}]`,'g'),'')

Attempt This Online!

Rust, 20 bytes

str::matches::<&[_]>

Attempt This Online!

This mixes up three I/O methods for strings: the first parameter is a plain string slice &str, the second is a slice of chars &[char], and the output is an iterator yielding single-char string slices impl Iterator<Item=&str>.

Doc for str::matches. It can take several kinds of patterns (i.e. anything that implements Pattern) for non-overlapping substring search:

We use the third variety in this challenge, which is indicated by the ::<&[_]> part. _ is a kind of wildcard type, and it resolves to char by the compiler because &[char] is the only type matching &[_] that implements Pattern.

PARI/GP, 27 bytes

f(a,b)=[c|c<-a,[d==c|d<-b]]

Attempt This Online!

Input and output lists of characters.

Wolfram Language (Mathematica), 16 bytes

Cases[#|##&@@#]&

Try it online!

Input and output two lists of characters [alphabet][string].

Factor, 6 bytes

within

Try it online!

Brachylog, 4 bytes

dᵗ∋ᵛ

Try it online!

Takes a list [s, a], and generates a list constituting the projection.

dᵗ      Deduplicate a,
  ∋ᵛ    then yield some c from a pair of elements [c, c] from s and a.

Deduplicating a is necessary in order to not generate multiple pairs from the same element of s.

Knight, 63 bytes

;=aP;=bP Wa;=c b;=dF;Wc;I?AcAa=dT0=cGc 1Lc;IdO+A Aa"\"0=aGa 1La

Try it online!

Haskell, 16 bytes

filter.flip elem

Try it online!

Takes arguments in reverse order.

Vyxal r, 3 bytes

F¹F

Try it Online!

Unfortuantely, the builtin doesn't work with duplicates.

R, 15 bytes

\(s,a)s[s%in%a]

Attempt This Online!

Takes input and outputs through vectors of character codes (as in linked test suite) or vectors of characters.

Rust, 70 bytes

|a:&str,b:&[u8]|a.bytes().filter(|d|b.contains(d)).collect::<Vec<_>>()

Attempt This Online!

Haskell, 20 bytes

a#b=filter(`elem`b)a

J, 5 4 bytes

e.#[

Try it online!

-1 byte thanks to seeing the word "filter" in Jonathan's Jelly answer

Filter by # element of e..

Jelly, 1 byte

f

Try it online!

This is exactly what Jelly's "filter-keep" dyadic atom does - takes a list on the left and a list on the right and keeps those in the left that appear in the right.

Dyalog APL, 1 byte

Attempt This Online!