[Question]
  [
## *Why was 6 afraid of 7? Because 7 8 9!*
Given a string apply the following transformations:
* If there is a 6 next to a 7 remove the 6 (6 is afraid of 7)
* If the sequence "789" appears remove the 8 and the 9 (7 ate 9)
(If I'm not mistaken it doesn't matter what order you do the transformations in)
Keep applying these transformations until you can no longer.
Example:
`78966` 
First we see "789", so the string becomes "766". Then we see "76", so we take out the 6, and the string becomes "76". Then we see "76" again, so we are left with "7".
Test Cases:
* `987` => `987` (Not in the right order. Does nothing.)
* `6 7` => `6 7` (The whitespace acts as a buffer between 6 and 7. Nothing happens)
* `676` => `7`
* `7896789` => `77`
* `7689` => `7`
* `abcd` => `abcd`
  
[Answer]
# [Retina](https://github.com/mbuettner/retina), 12
Translation of the sed answer:
```
6*7(6|89)*
7
```
[Try it online](http://retina.tryitonline.net/#code=Nio3KDZ8ODkpKgo3&input=OTg3CjYgNwo2NzYKNzg5Njc4OQo3Njg5CmFiY2QKNjg5Nzg5NjY4OTc4OTYKNjc3ODk)
[Answer]
# Javascript ES6, 29 bytes
```
s=>s.replace(/6*7(89|6)*/g,7)
```
Test:
```
f=s=>s.replace(/6*7(89|6)*/g,7)
;`987 -> 987
6 7 -> 6 7
676 -> 7
7896789 -> 77
7689 -> 7
abcd -> abcd`
.split`\n`.every(t=>(t=t.split` -> `)&&f(t[0])==t[1])
```
[Answer]
# Java, ~~126~~ ~~81~~ ~~66~~ 58 bytes
Thanks to @GamrCorps for providing the lambda version of this code!
Thanks to @user902383 for pointing out an autoboxing trick!
...yup.
It's actually longer than I expected - Java replaces items in strings with `replaceAll()` once per match, not repeatedly until it stops changing. So I had to use a fancy for loop.
### Lambda form:
```
x->{for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
```
### Function form:
```
String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
```
### Testable Ungolfed Code:
```
class B{
    public static void main(String[]a){
        System.out.print(new B().s(a[0]));
    }
    String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;}
}
```
[Answer]
# GNU Sed, 17
Score includes +1 for `-r` option.
```
s/6*7(6|89)*/7/g
```
[Answer]
# [Perl 6](http://perl6.org),  ~~19~~  18 bytes
```
{S:g/6*7[6|89]*/7/} # 19 bytes
```
```
$ perl6 -pe 's:g/6*7[6|89]*/7/' # 17 + 1 = 18 bytes
```
( Note that `[6|89]` is the non-capturing version of `(6|89)` which is spelt as `(?:6|89)` in Perl 5. `<[6|89]>` is how you would write what's spelt as `[6|89]` in Perl 5)
usage:
```
$ perl6 -pe 's:g/6*7[6|89]*/7/' <<< '
987
6 7
6676689
7896789
7689
abcd
68978966897896
79|689
'
```
```
987
6 7
7
77
7
abcd
68977
79|689
```
[Answer]
# Pyth, 17 bytes
```
u:G"67|76|789"\7z
```
[Try it here.](http://pyth.herokuapp.com/?code=u%3AG%2267%7C76%7C789%22%5C7z&test_suite=1&test_suite_input=987%0A6+7%0A676%0A7896789%0A7689%0Aabcd)
Leaky Nun has outgolfed this by a byte in the comments.
[Answer]
# [Perl 5](http://perl.org), 17 bytes
```
perl -pe 's/6*7(6|89)*/7/g' # 16 + 1
```
usage:
```
$ perl -pe 's/6*7(6|89)*/7/g' <<< '
987
6 7
6676689
7896789
7689
abcd
68978966897896
'
```
```
987
6 7
7
77
7
abcd
68977
```
[Answer]
## Mathematica, 52 bytes
```
StringReplace[#,"67"|"76"|"789"->"7"]&~FixedPoint~#&
```
Explanation:
```
                                                   &   A function returning
                                     &                   a function returning
              #                                            its first argument
StringReplace[ ,                    ]                     with
                "67"                                        "67"
                    |                                      or
                     "76"                                   "76"
                         |                                 or
                          "789"                             "789"
                               ->                         replaced with
                                 "7"                       "7"
                                    ~FixedPoint~        applied to
                                                #        its first argument
                                                        until it no longer changes.
```
[Answer]
## Rust, 96 bytes
```
fn f(mut s:String)->String{for _ in 0..s.len(){for r in&["67","76","789"]{s=s.replace(r,"7")}}s}
```
Hopelessly long, as per usual for Rust...
Ungolfed:
```
fn seven_ate_nine(mut str: String) -> String {
    for _ in 0..str.len() {
        for to_replace in &["67","76","789"] {
            str = str.replace(to_replace, "7");
        }
    }
    s
}
```
[Answer]
# Emacs Lisp, 59 bytes
```
(lambda(s)(replace-regexp-in-string"6*7\\(6\\|89\\)*""7"s))
```
It becomes a bit clearer with spaces:
```
(lambda (s) (replace-regexp-in-string "6*7\\(6\\|89\\)*" "7" s))
```
[Answer]
# Ruby, 27 bytes
This solution is from comments, credit to *Brad Gilbert b2gills*.
```
->s{s.gsub /6*7(6|89)*/,?7}
```
---
## Ruby, 37 bytes
***(old solution)***
This solution uses the fact that you will never need to replace more times than characters in the string.
```
->s{s.chars{s.sub! /67|76|789/,?7};s}
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 bytes
```
jt"'789|76'55cYX]
```
### Example
```
>> matl
 > jt"'789|76'55cYX]
 > 
> 7896789
77
```
**EDIT**: [**Try it online!**](http://matl.tryitonline.net/#code=anQiJzc4OXw3Nic1NWNZWF0&input=Nzg5Njc4OQ)
### Explanation
```
j                   % input string
t                   % duplicate
"                   % for each character. Iterates as many times as the string length
    '789|76'        % regular expression for replacement
    55c             % string to insert instead: character '7'
    YX              % regexprep
]                   % end for
```
This works by applying a regular expresion replacement for *as many times as there are characters in the original string*. This is enough, since each substitution reduces the number of characters.
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 15 bytes
```
Ur"6*7(89|6)*"7
```
Simple RegEx solution 
[Try it online](http://ethproductions.github.io/japt?v=master&code=VXIiNio3KDg5fDYpKiI3&input=Ijc4OTY3ODki)
[Answer]
# PowerShell, 27 bytes
```
$args-replace'6*7(89|6)*',7
e.g.
PS C:\temp> .\ate.ps1 "7689"
7
PS C:\temp> .\ate.ps1 "abcd"
abcd
PS C:\temp> .\ate.ps1 "68978966897896"
68977
```
Making use of:
* someone else's regex pattern
* the way `-replace` does a global replace by default in PowerShell
* loop unrolling, where it will apply the `-regex` operator to the array `$args` by applying it to all the elements individually, and there's only one element here because there's only one script parameter, so it works OK and we can avoid having to index element `[0]`.
---
Novelty previous attempt before realising a global replace would do it; 74 bytes of building a chain of "-replace -replace -replace" using string multiplication, as many times as the length of the string, then eval()ing it:
```
"'$($args)'"+("{0}6|6(?=7)'{0}89'"-f"-replace'(?<=7)")*$args[0].Length|iex
```
(With a bit of string substitution to shorten the number of replaces).
[Answer]
## Seriously, 29 bytes
```
,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n
```
Takes input as a double-quoted string, like `"6789"`. [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b6c6027373b3b22363722289222373622289222373839222892606e&input=6789) (you will need to manually quote the input).
Explanation:
```
,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n
,;l                            get input and push its length (we'll call it n)
   `                       `n  call the following function n times:
    '7;;"67"(Æ                   replace all occurrences of "67" with "7"
              "76"(Æ             replace all occurrences of "76" with "7"
                    "789"(Æ      replace all occurrences of "789" with "7"
```
[Answer]
## PHP, 36 bytes
```
preg_replace('/6*7(6|89)*/','7',$a);
```
regex solution, takes $a string and replaces via the expression.
[Answer]
# [Thue](https://en.wikipedia.org/wiki/Thue_%28programming_language%29), 26 bytes
```
67::=7
76::=7
789::=7
::=
```
including a trailing newline.
Input is appended to the program before starting it.  
Output is read off the program state when it terminates, similarly to a Turing machine.  
(Thue *does* have an output stream, but it's difficult to use correctly, so I'm not sure whether this is an acceptable output method)
[Answer]
## CJam, ~~70~~ 64 bytes
Thanks to @Peter Taylor for cutting `{"789":I}{"76:":I}?` to `"789""76"?:I` 
`~~"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I={"789":I}{"76":I}?];}?}/A~~`
`"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I="789""76"?:I];}?}/A`
I know this could probably be golfed a lot further and your help would be greatly appreciated, but frankly I'm just happy I managed to get the answer. This was my first attempt at writing CJam.
Explanation:
```
"67":I                e# Assign the value of 67 to I
q:A                   e# Read the input and assign to A
{                     e# Opening brackets for loop
    AI#:B)            e# Get the index of I inside A and assign to B. The increment value by 1 to use for if condition (do not want to process if the index was -1)
    {                 e# Open brackets for true result of if statement
        AB<           e# Slice A to get everything before index B
        7+            e# Append 7 to slice
        A{BI,+}~>     e# Slice A to get everything after index B plus the length of string I (this will remove I entirely)
        +s:A          e# Append both slices, convert to string, and assign back to A
        ];            e# Clear the stack
    }                 e# Closing brackets for the if condition
    {                 e# Open brackets for false result of if statement
        "76"I=        e# Check if I is equal to 76
        "789"         e# If I is 76, make I 789
        "76"?:I       e# If I is not 76, make I 76
        ];            e# Clear the stack if I does not exist inside A
    }?                e# Closing brackets for false result of if statement
}/                    e# Loop
A                     e# Output A
```
[Answer]
## R, 35 bytes
```
cat(gsub("6*7(6|89)*",7,scan(,"")))
```
I didn't know I could use `gsub` this way, a big thank you for every answer here that made me learn something new.
[Answer]
## Python 3, 46 bytes
```
import re
lambda s:re.sub(r'6*7(6|89)*','7',s)
```
[Answer]
# [Dyalog APL](https://dyalog.com), 17 bytes
```
'6*7(6|89)*'⎕R'7'
```
`'6*` any number of sixes  
`7` followed by a seven  
`(`…`)*'` followed by zero or more sequences of…  
 `6|89` a six or eight-nine
`⎕R` **R**eplace that with
`'7'` a seven
[Answer]
# [///](https://esolangs.org/wiki///), 19 bytes
```
/67/7//76/7//789/7/
```
You can't actually provide input in this language, so the supposed input goes to the right of the code, which is allowed by recent rules.
[Answer]
## **PHP 51 characters**
```
while($s!=$r=str_replace([789,67,76],7,$s)){$s=$r;}
```
**Test case written in long hand**
```
$s = '78966';
while ($s != $r = str_replace([789, 67, 76], 7, $s) )
{
    $s = $r;
}
echo $s; // 7;
```
This does the string comparison and the string replace both in the while condition. If while condition is met, it updates the left hand of the comparison with the result. Let me know of any improvements.
[Answer]
# [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 15 bytes
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cGkiNio3KDZ8ODkpKiI3) Do I really have to explain?
```
pi"6*7(6|89)*"7
p               replace any entity in
 i               the input
  "6*7(6|89)*"   that matches this regex
              7  with 7
                implicit output
```
[Answer]
## Clojure, 71 bytes
Clojure is less-than-ideal for golfing due to its verbose nature - but nonetheless it's an interesting exercise:
Golfed version, using Java interop:
```
(defn f[s](let[x(.replaceAll s "67|76|789" "7")](if(= s x)s(recur x))))
```
Un-golfed version, using Java interop:
```
(defn six-fears-seven [s]
  (let [x (.replaceAll s "67|76|789" "7")]
    (if (= s x)
      s
      (recur x))))
```
Un-golfed "pure Clojure" version:
```
(defn six-fears-seven [s]
  (let [x (clojure.string/replace s #"67|76|789" "7")]
    (if (= s x)
      s
      (recur x))))
```
[Answer]
# Bash, 102 82 67 (+7)? bytes
### extglob version
```
x=$1
while v=${x/@(76|67|789)/7};[ $v != $x ];do x=$v;done
echo $v
```
This is meant to be put in a file and called with e.g. `bash -O extglob 789.sh 6567678989689789656`. The (+7)? bytes is for if the extglob option counts toward bytes.
Thanks to @BinaryZebra for pointing out extglob features!
---
### Non-extglob version (82 bytes)
```
x=$1
while v=${x/76/7};v=${v/67/7};v=${v/789/7};[ $v != $x ];do x=$v;done
echo $v
```
This is meant to be put in a file and called with e.g. `./789.sh 65678989656`.
It makes use of parameter expansion to search and replace in a loop. I involved a series of expansions to do the replacing since I'm not aware of a way to more effectively chain expansions.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 12 bytes
```
e/6?7(6|89/7
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS82PzcoNnw4OS83&input=LW1SIFsKIjc4OTY2IiwKIjk4NyIsCiI2IDciLAoiNjc2IiwKIjc4OTY3ODkiLAoiNzY4OSIsCiJhYmNkIiwKIjY4OTc4OTY2ODk3ODk2Igpd)
### How it works
`String.e` is recursive replace function. Japt 2 has a new regex syntax and auto-completion of parentheses inside regex, which saves one byte here. (In Japt 1.x, we had to pass strings in place of regexes, which was kinda clunky.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ67Â‚789ª7:
```
[Try it online](https://tio.run/##yy9OTMpM/f//3BQz88NNjxpmmVtYHlplbvX/P5BhBkYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVulir6TwqG2SgpL9/3NTzMwPNz1qmGVuYXlolbnV/1qd/5YW5lxmCkBsbsYFFDYDYi5zMyCRmJScwmUI5BqbmxlBpMyBisyA2BzMBSMuIAZxoBQA).
**Explanation:**
```
Δ            # Continue doing the following until it no longer changes:
 67          #  Push 67 to the stack
   Â         #  Bifurcate (short for Duplicate & Reverse copy): 76
    ‚        #  Pair them together: [67,76]
     789ª    #  Append 789 to this list: [67,76,789]
         7:  #  Replace all occurrences of these three integers with 7
             #   i.e. 1789372 → 17372
             # (after the loop, output the result after implicitly)
```
`67Â‚789ª` could alternatively be `•4BĆx•₄в` for the same byte-count.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 27 bytes
```
{x{"7"/y@x}/(\'$67 76 789)}
```
[Try it online!](https://ngn.codeberg.page/k#eJxFkVFrwyAQx9/9FIcUlsISBwNtEzb2sOc+7a0r1CYaQzvN1JKE0n32qU03UP78f96d3inLy3jBDJPpbbyS7PNhQRkwCmy1Xl4R8uVlsZ1+bCkBYKz25lhle8m7UzVWU2WXuyvy23AEeL1iuJp1d4ehToJR/yGjEcIjvkEc7qJhJ4jZXyRmdIb3yAj5oW4CvOkOIYKU970rCalNI1pzkoXzvD6KsVZct6KozRf5PgvnO6MdoZQ+PZNBTfnAXU5zLi3vmtzInCGE4vtCA/DymiTbGA+dBq8E2K5VHoxthC3g3QgH2njV6bZYprTQYkyLkn2E+EF1Xrie1wJ47R3wsOBwllJYOAg/CKFDMNcNsAI2t1KgeN8L7eaK4RtCRZbMPKMEZkJnm1wcR3RREfoFlgR8jQ==)
* `$67 76 789` shorthand for `("67";"76";"789")`
* `(\'...)` create list of splitter functions, i.e. `("67"\;"76"\";"789"\)`
* `x{...}/(...)` set up a reduce, seeded with `x` (the input), run over the list of splitter functions
	+ `{"7"/y@x}` split the input (`x`) using the current splitter function (`y`), then join the result with `"7"`. feed this to the next iteration of the reduce
]