Trasformazione magica dell'email! Oppure: aiuta l'NSA a estrarre i metadati dal tuo indirizzo email


17

Dato un indirizzo e-mail, il risultato di una trasformazione applicata a quell'indirizzo e-mail e un secondo indirizzo e-mail restituiscono l'output della stessa trasformazione applicata al secondo indirizzo e-mail.

Gli indirizzi email avranno tutti la seguente struttura:

Una stringa di lunghezza positiva contenente caratteri alfanumerici e al massimo una .(la parte locale), seguita da un @simbolo, seguita da una stringa di lunghezza positiva contenente sumboli alfanumerici (il dominio), seguito da un. simbolo e da una stringa finale di lunghezza positiva contenente caratteri alfanumerici (TLD).

Esistono quattro trasformazioni consentite:

  • Identità (nessun cambiamento). (a.b@c.d -> a.b@c.d )
  • Restituzione solo della parte locale (tutto prima del @) non modificata (a.b@c.d -> a.b ).
  • Restituendo la parte locale divisa sul .se presente, con il primo simbolo di ciascuna metà maiuscola. (a.b@c.d -> A B ).
  • Restituisce solo il dominio (tutto tra il @e il finale .) non modificato. ( a.b@c.d -> c).

Quando è possibile più di una trasformazione, è possibile fornire l'output di una qualsiasi delle possibilità. Gli spazi bianchi all'inizio e alla fine dell'output non contano, ma nel mezzo importa (cioè se ci si divide a.bin A Bdovrebbe esserci solo uno spazio nel mezzo [e qualsiasi numero all'inizio e alla fine dell'output], ma se si divide a., quindi Acon qualsiasi numero di spazi su entrambi i lati sono tutti accettabili).

Esempi ( input | output):

john.doe@gmail.com, John Doe, phillip.maini@gmail.com         | Phillip Maini
John.Doe@gmail.com, John Doe, Phillip.Maini@gmail.com         | Phillip Maini
foo.bar@hotmail.com, foo.bar, gee.whizz@outlook.com           | gee.whizz
foo.bar@hotmail.com, foo.bar, gEe.Whizz@outlook.com           | gEe.Whizz
rodney.dangerfield@comedy.net, comedy, michael.scott@office.0 | office
.jones@x.1, Jones, a.@3.z                                     | A
.jones@x.1, .jones@x.1, a.@3.z                                | a.@3.z
.jones@x.1, .jones, a.@3.z                                    | a.
.jones@x.1, x, a.@3.z                                         | 3
.@b.c, .@b.c, 1@2.3                                           | 1@2.3
john.jones@f.f, John Jones, 1in.thehand@2inthe.bush           | 1in Thehand
chicken.soup@q.z, Chicken Soup, fab@ulou.s                    | Fab
lange@haare.0, lange, fat.so@fat.net                          | fat.so
Lange@haare.0, Lange, fat.so@fat.net                          | {fat.so, Fat So} # either acceptable
chicken@chicken.chicken, chicken, horse@pig.farm              | {horse, pig} # either acceptable

Si applicano le solite regole e lacune.


L'ultimo caso di test non dovrebbe restituire "cavallo"? Invece non vedo perché possa restituire "maiale".
Erik the Outgolfer,

3
@EriktheOutgolfer perché la 4a trasformazione è di restituire solo il dominio (la parte tra @e finale .). Poiché la parte locale e il dominio sono entrambi chicken, è ambiguo che si tratti della 2a o 4a trasformazione
LangeHaare,

Oh, l'ho interpretato male.
Erik the Outgolfer,

Potremmo richiedere che l' input pertinente sia formattato con lo spazio in tutti i casi (ad esempio nel test in cui l'output è A[con uno spazio finale] che il secondo input sia Jones[con uno spazio iniziale])?
Jonathan Allan,

Non capisco il motivo per cui .jones@x.1, Jones, a.@3.zè A- se jonesè compensata che indica la parte di corrispondenza è la parte tra il primo periodo e il simbolo @. Ma ciò comporterebbe una stringa vuota perché aè prima del primo periodo e non dopo.
Jerry Jeremiah,

Risposte:


4

Java 8, 254 240 236 byte

(a,b,c)->{String A[]=a.split("@"),C[]=c.split("@"),x="";for(String p:C[0].split("\\."))x+=(p.charAt(0)+"").toUpperCase()+p.substring(1)+" ";return a.equals(b)?c:A[0].equals(b)?C[0]:A[1].split("\\.")[0].equals(b)?C[1].split("\\.")[0]:x;}

-4 byte grazie a @LukeStevens .

Spiegazione:

Provalo qui.

(a,b,c)->{                  // Method with three String parameters and String return-type
  String A[]=a.split("@"),  //  Split `a` by "@" into two parts
         C[]=c.split("@"),  //  Split `c` by "@" into two parts
         x="";              //  Temp-String
  for(String p:C[0].split("\\.")) 
                            //  Loop over the first part of `c`, split by dots
    x+=                     //   Append String `x` with:
       (p.charAt(0)+"").toUpperCase()
                            //    The first character as uppercase
       +p.substring(1)      //    + the rest of the String
       +" ";                //    + a space
                            //  End of loop (implicit / single-line body)
  return a.equals(b)?       //  If input `a` and `b` are exactly the same:
    c                       //   Return `c`
   :A[0].equals(b)?         //  Else-if the first part of `a` equals `b`:
    C[0]                    //   Return the first part of `c`
   :A[1].split("\\.)[0].equals(b)?
                            //  Else-if the domain of `a` equals `b`
    C[1].split("\\.)[0]     //   Return the domain of `c`
   :                        //  Else:
    x;                      //   Return String `x`
}                           // End of method

1
Puoi eliminare 4 byte usando (p.charAt(0)+"").toUpperCase()invece di Character.toUpperCase(p.charAt(0)).
Luke Stevens,

@LukeStevens Grazie! All'inizio l'ho avuto (char)(p.charAt(0)&~32), ma questo non ha funzionato a causa del 1in Thehandtest case. Ma aumentarlo come String è effettivamente più breve di Character.toUpperCase, quindi grazie!
Kevin Cruijssen,

3

Haskell , 208 byte

import Data.Char
s c""=[]
s c a=w:f t where
 (w,t)=span(/=c)a
 f(_:y)=s c y
 f _=[]
h=head
u""=""
u(x:y)=toUpper x:y
l=h.s '@'
f x y=h[t|t<-[id,l,unwords.filter(/="").map u.s '.'.l,h.s '.'.last.s '@'],t x==y]

Provalo online!

È triste che ho dovuto spendere 59 byte per reinventare split(s ).

La soluzione crea un elenco di trasformazioni e restituisce la prima che porta al risultato previsto.


Benvenuti nel sito! Non conosco Haskell, ma è possibile rimuovere uno qualsiasi dei caratteri degli spazi bianchi, come nuove linee e spazi?
caird coinheringaahing

Bella prima risposta! Potresti essere interessato alla nostra raccolta di suggerimenti per il golf a Haskell , in particolare questo e questo dovrebbe risparmiare alcuni byte.
Laikoni,

Inoltre, sentiti libero di unirti a noi in Of Monads and Men , una chat room per il golf e discussioni generali su Haskell.
Laikoni,

3

Gelatina , 40 byte

Prevenzione grazie a Erik the Outgolfer per aver notato il fallimento dell'utilizzo Œt(title-case) e quindi Œu1¦€KoltreŒtK

-1 byte grazie a Erik the Outgolfer (riorganizzazione di ⁵⁸ç⁹¤Ŀa çµ⁵⁸Ŀ)


ÑṪṣ”.Ḣ
ṣ”@
ÇḢ
Çṣ”.Œu1¦€K
⁹ĿðЀ5i
çµ⁵⁸Ŀ

Una presa programma completo exampleEmail, exampleOutput, realEmaile stampare il risultato.

Provalo online!

Come?

Esegue tutte e quattro le trasformazioni (più una precursore), trova la prima che fornisce l'esempio dalla prima e-mail, quindi la applica alla seconda e-mail:

            - Link 1, do nothing: email
            - do nothing but return the input

ÑṪṣ”.Ḣ      - Link 2, the domain: email
Ñ           - call the next link (3) as a monad (split at "@")
 Ṫ          - tail
  ṣ”.       - split at "."
     Ḣ      - head

ṣ”@         - Link 3, split at @: email
ṣ”@         - split at "@"

ÇḢ          - Link 4, local part: email
Ç           - call the last link (3) as a monad (split at "@")
 Ḣ          - head

Çṣ”.Œu1¦€K  - Link 5, name-ified: email
Ç           - call the last link (4) as a monad (get the local part)
 ṣ”.        - split at "."
       ¦€   - for €ach sparsley apply:
      1     - ...to index: 1
    Œu      - ...action: uppercase
         K  - join with space(s)

⁹ĿðЀ5i     - Link 6, index of first correct link: exampleEmail; exampleOutput
   Ѐ5      - map across (implicit range of) 5 (i.e. for each n in [1,2,3,4,5]):
  ð         -   dyadicly (i.e. with n on the right and exampleEmail on the left):
 Ŀ          -     call referenced link as a monad:
⁹           -     ...reference: chain's right argument, n
      i     - first index of exampleOutput in the resulting list

çµ⁵⁸Ŀ       - Main link: exampleEmail; exampleOutput
ç           -   call the last link (6) as a dyad (get the first "correct" link index)
 µ          - monadic chain separation (call that L)
   ⁸        - chain's left argument, L
    Ŀ       - call the link at that reference as a monad with input:
  ⁵         -   program's third input, realEmail

Appunti:

  1. Presuppone l'esempio di input L'output è esattamente lo stesso dell'output.

  2. Il "precursore" (il risultato del collegamento 3) viene testato per la corrispondenza di exampleOutput, ma non corrisponderà a meno che il se exampleOutputstesso non sia un elenco di elenchi di caratteri. Pertanto, gli input dovrebbero essere probabilmente citati (la formattazione Python può essere utilizzata qui) per evitare la possibilità di interpretarli come tali.




2

JavaScript (ES6), 145 byte

Richiamare con la sintassi del curry, ad es f('chicken.soup@q.z')('Chicken Soup')('fab@ulou.s')

x=>y=>[x=>x,s=x=>x.split`@`[0],x=>s(x).split`.`.map(w=>w&&w[0].toUpperCase()+w.slice(1)).join` `.trim(),x=>/@(.+)\./.exec(x)[1]].find(f=>f(x)==y)


1

Mathematica, 217 byte

(L=Capitalize;T@x_:=(M=StringSplit)[x,"@"];P@x_:=#&@@T[x];W@x_:=If[StringContainsQ[P@x,"."],StringRiffle@L@M[P@x,"."],L@P@x];Z@x_:=#&@@M[T[x][[2]],"."];If[#==#2,#3,If[#2==P@#,P@#3,If[#2==W@#,W@#3,If[#2==Z@#,Z@#3]]]])&


Provalo online!



1

CJam, 42

q~@{[_\'@/~'./0=\_'.%{(eu\+}%S*]}:T~@a#\T=

Provalo online

Spiegazione:

q~        read and evaluate the input (given as 3 quoted strings)
@         bring the first string to the top of the stack
{…}:T     define a function T that calculates the 4 transformations of a string:
  [       begin array
  _\      duplicate the string, and swap with the other copy to bring it in the array
           (1st transformation)
  '@/~    split by '@' and put the 2 pieces on the stack
  './0=   split the 2nd piece by '.' and keep the first part
           (4th transformation)
  \_      swap with the piece before '@' and duplicate it
           (2nd transformation)
  '.%     split by '.', removing the empty pieces
  {…}%    transform the array of pieces
    (eu   take out the first character and capitalize it
    \+    prepend it back to the rest
  S*      join the pieces by space
           (3rd transformation)
  ]       end array
~         execute the function on the first string
@a        bring the 2nd string to the top of the stack, and wrap it in an array
#         find the position of this string in the array of transformations
\T        bring the 3rd string to the top and call function T
=         get the transformation from the array, at the position we found before

1

PHP 7.1, 176 byte

<?$e=explode;[,$p,$q,$r]=$argv;echo$p==$q?$r:($e('@',$p)[0]==$q?$e('@',$r)[0]:($e('.',$e('@',$p)[1])[0]==$q?$e('.',$e('@',$r)[1])[0]:ucwords(join(' ',$e('.',$e('@',$r)[0])))));

Provalo online!

PHP <7.1, 180 byte

Le versioni in 7.1 dovrebbero cambiare [,$p,$q,$r]=$argvin list(,$p,$q,$r)=$argv, aggiungendo 4 byte.


1

GNU sed , 105 + 1 (flag r) = 106 byte

I primi tre scomandi verificano rispettivamente le trasformazioni di identità , parte locale e dominio . Se una trasformazione corrisponde, viene applicata al secondo indirizzo e-mail e i seguenti scomandi falliranno a causa della mancanza del formato di input.

s:^(.*),\1,::
s:(.*)@.*,\1,(.*)@.*:\2:
s:.*@(.*)\..*,\1,.*@(.*)\..*:\2:
s:.*,([^.]*)\.?(.*)@.*:\u\1 \u\2:

Provalo online!

La trasformazione suddivisa in parti locali (ultimo scomando) è la più costosa da controllare, in termini di byte, quindi l'ho posizionata alla fine e ho ipotizzato che corrispondesse (poiché le altre fallivano in quel momento), andando direttamente alla sua applicazione.


1

Gelatina , 43 byte

ḢŒlṣ”.Œu1¦€K
ṣ”@Wẋ4j”@$ḷ/ÇṪṣ”.Ḣ$$4ƭ€
Çiị⁵Ǥ

Provalo online!


Funzionerebbe ŒtKal posto di Œu1¦€Ksalvare 3?
Jonathan Allan,

... e qual è la necessità Œl?
Jonathan Allan,

^ ah vedo che 1in.thehandnon funzionerebbe ŒtK.
Jonathan Allan,

@JonathanAllan Sì, questo è il motivo per cui non l'ho usato, e anche il motivo per cui la risposta di ovs (ora cancellata) non era valida ( str.title).
Erik the Outgolfer,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.