[Question]
  [
In English, there is the fun and simple difference between `an` and `a`: you use `an` when preceding a word starting with a vowel sound, and `a` when the word starts with a consonant sound. 
For the sake of simplicity in this challenge, `an` precedes a word that starts with a vowel (`aeiou`), and `a` precedes a word that starts with a consonant. 
**Input**
A string comprising only printable ASCII characters, with `[?]` appearing in places where you must choose to insert `an` or `a`. `[?]` will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal. 
**Output**
The input string with `[?]` replaced with the appropriate word (`an` or `a`). You do have to worry about capitalization!
**When to Capitalize**
Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of `.?!` followed by a space. 
**Examples**
```
Input: Hello, this is [?] world!
Output: Hello, this is a world!
Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.
Input: [?] giant en le sky.
Output: A giant en le sky.
Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!
Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.
Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!**
  
[Answer]
# Perl, 48 bytes
*Saved 1 byte due to [Ton Hospel](https://codegolf.stackexchange.com/posts/comments/227428?noredirect=1).*
```
#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg
```
Counting the shebang as one, input is taken from stdin.
**Explanation**
```
#!perl -p               # for each line of input, set $_, auto-print result
s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an
;eg                     # regex options eval, global
```
**Sample Usage**
```
$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!
$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.
$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?
$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.
```
[Answer]
# Ruby, ~~78~~ 72 bytes
```
->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}
```
* Saved 6 bytes thanks to [@Jordan](https://codegolf.stackexchange.com/users/11261/)
**Ungolfed**
```
def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 41 bytes
```
√ç√£√õ?√ù ¬®[aeiou]¬©/an
√ç√õ?√ù/a
√ç^a√º[.!?] a/A
```
[Try it online!](http://v.tryitonline.net/#code=w43Do8ObP8OdwoUgwqhbYWVpb3VdwqkvYW4Kw43Dmz_DnS9hCsONXmHDvFsuIT9dIMKTYS9B&input=SGVsbG8sIHRoaXMgaXMgWz9dIHdvcmxkIQpIb3cgYWJvdXQgd2UgYnVpbGQgWz9dIGJpZyBidWlsZGluZy4gSXQgd2lsbCBoYXZlIFs_XSBvcmFuZ2UgYmFuYW5hIGhhbmdpbmcgb3V0IG9mIFs_XSB3aW5kb3cuCls_XSBnaWFudCBlbiBsZSBza3kuCls_XSB5YXJuIGJhbGw_Cls_XSBob3VyIGFnbyBJIG1ldCBbP10gRXVyb3BlYW4u), which conveniently can also be used to verify all test cases with no extra byte count.
This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump:
```
0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A
```
[Answer]
# PHP, 207 bytes
```
foreach(explode("[?]",$s)as$i=>$b){$r=Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])].n[!preg_match("#^['\"¬¥`\s]*([aeiou]|$)#i",$d=trim($b))];echo$i?$r.$b:$b;$a=$i?''==$d?a:$b:(''==$d?".":a);}
```
I like solutions more complete from time to time ...  
but I must admit that this is a little overkill, although it¬¥s not at all finished.
Save to file, run with `php <filename>` with input from STDIN.
**test cases**
```
How about we build [?] big building ... with [?] orange banana hanging out of [?] window.
=>  How about we build a big building ... with an orange banana hanging out of a window.
Hello, this is [?] world!               =>  Hello, this is a world!
Should I use [?] '[?]' or [?] '[?]'?    =>  Should I use an 'an' or an 'a'?
[?] elephant in [?] swimsuit.           =>  An elephant in a swimsuit.
How I met your moth[?].                 =>  How I met your motha.
b[?][?][?] short[?]ge!                  =>  banana shortage!
```
**breakdown**
```
foreach(explode("[?]",$s)as$i=>$b)
{
    $r=
        // lookbehind: uppercase if the end of a sentence precedes
        Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])]
        .
        // lookahead: append "n" if a vowel follows (consider quote characters blank)
        n[!preg_match("#^['\"¬¥`\s]*([aeiou]|$)#i",$d=trim($b))]
    ;
    // output replacement and this part
    echo$i?$r.$b:$b;
    // prepare previous part for next iteration
    $a=$i               // this part was NOT the first:
        ?   ''==$d
            ? a             // if empty -> a word ($r from the previous iteration)
            : $b            // default: $b
        :  (''==$d      // this WAS the first part:
            ? "."           // if empty: end of a sentence (= uppercase next $r)
            : a             // else not
        )
    ;
    // golfed down to `$a=!$i^''==$d?a:($i?$b:".");`
}
```
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 75 bytes
```
od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=od4%26r%24O%2E%22%5D%3F%5B%2230%24Z3%2600w4X%22Aa%22I2-%22Aa%20%2E%2240%24Z%2C*2%26%24rxr%24O%22%20aeiou%22od0Z1%3D3%26%22n%22r5X%24r&input=%5B%3F%5D%20example%3A%20How%20about%20we%20build%20%5B%3F%5D%20big%20building%2E%20It%20will%20have%20%5B%3F%5D%20orange%20banana%20hanging%20out%20of%20%5B%3F%5D%20window%2E%20%5B%3F%5D%20example%2E)
### Explanation
```
od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.
    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box
                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0
                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack
```
Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try.
[Answer]
# JavaScript (ES6), 90  ~~86 87 85~~
*Edit once more* as the spec for capitalization has changed (more sensible now)
*Edit again* 1 byte save thx @Huntro
*Edit* 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85
~~Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)~~
```
x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))
```
**Test**
```
f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))
function go() {
  var i=I.value, o=f(i)
  O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML 
}
go()
```
```
#I { width:80% }
```
```
<input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O></pre>
```
[Answer]
## Batch, 136 bytes
```
@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%
```
Takes a line of input on STDIN.
[Answer]
# PHP, ~~100~~ 92 bytes
```
<?=preg_filter(["/\[\?]\K(?= [aeiou])/i","/([.?!] |^)\K\[\?]/","/\[\?]/"],[n,A,a],$argv[1]);
```
It was possible to further golf the regular expressions.
Gives a notice about an undefined constant but still works.
Edit: 8 bytes saved thanks to primo
[Answer]
# Java, ~~180~~178 bytes
My first post here, I did use a part of the **Kevin Cruijssen** post but and up with a different approach, he helped me to reduce a bit more so, thanks to him !
```
String c(String s){String x[]=s.split("\\[\\?]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;}
```
Here it is ungolfed :
```
static String c(String s) {
        String x[] = s.split("\\[\\?\\]", 2), r = x[0];
        return x.length > 1 ? r + (r.matches("(.+[.!?] )|(^)$") ? "A" : "a")
                + ("aeiouAEIOU".contains("" + x[1].charAt(1)) ? "n" : "") + c(x[1]) : r;
    }
```
[And the result](https://ideone.com/3gG1Z1)
A simple explanation, I use a recursive approch to find every `[?]`.
I couldn't find a way to use the matches with insensitive case (not sure it is possible).
178bytes : Thanks to Martin Ender !
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2F≈æN≈æM‚ÄöN√®S√∞√¨‚Ä¶[?]¬©√¨Du¬´D¬Æ'a'nN√ó¬´::}.¬™
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyO3oPr@j@3wfNczyO7wi@PCGw2seNSyLto89tPLwGpfSQ6tdDq1TT1TP8zs8/dBqK6tavUOr/v8HSitUJhblKSQl5uTYK4C4SZnpCvl5qYpgTkZ@aZFCYnq@gqdCbmoJWMi1tCi/IDUxT@@/rm5evm5OYlUlAA) or [verify all test cases](https://tio.run/##PY@xTsNADIb3PIWbpUuagbFLloLagSDBWHVwmiM5cdjV5a5REEh9CyQeAAGtEBNjh0R9kb5IuCQSsgf//n7bMheYSNE@b/0FbayZAvhRFXj@jTW9dKq9uDod49Px@rx7i5uPu@anOZx378toVX82h5mt97P6e4xjipvXej@dvoT1VxvUv1E7F0pxACaXBbh0E1CyVunIm3MJmLA1UApIrFRpTxOZDUpSFsLCUakU5LgVPWaNlDk/kgvXpsz5oNvC98N2SSmXodfVmUQyIAiUgOKhGpoVanLzSkX/95jEqGc5Ww2YMSzgUZieX1rNG4EUenNRQSE1LG/lOkedrgLnL2Hc/9BZ12iidjIhnih8qv4A).
**Explanation:**
```
2F            # Loop 2 times:
  ≈æN          #  Push consonants "bcdfghjklmnpqrstvwxyz"
  ≈æM          #  Push vowels "aeiou"
    ‚Äö         #  Pair them together into a list
     N√®       #  And use the loop-index to index into this pair
  S           #  Convert this string to a list of characters
   √∞√¨         #  Prepend a space in front of each character
     ‚Ä¶[?]     #  Push string "[?]
         ¬©    #  Store it in variable `¬Æ` (without popping)
          √¨   #  And prepend it in front of each string in the list as well
  }D          #  Then duplicate the list
    u         #  Uppercase the characters in the copy
     ¬´        #  And merge the two lists together
              #   i.e. for the vowel-iteration we'd have ["[?] a","[?] e","[?] i","[?] o",
              #    "[?] u","[?] A","[?] E","[?] I","[?] O","[?] U"]
   D          #  Duplicate it
    ¬Æ         #  Push "[?]" from variable `¬Æ`
     'a      '#  Push "a"
       'n    '#  Push "n"
         N√ó   #  Repeated the 0-based index amount of times (so either "" or "n")
           ¬´  #  And append it to the "a"
    :         #  Replace all "[?]" with "an"/"a" in the duplicated list
     :        #  And then replace all values of the lists in the (implicit) input-string
 }.¬™          #  After the loop: sentence-capitalize everything (which fortunately retains
              #  capitalized words in the middle of sentences, like the "European" testcase)
              # (and after the loop the result is output implicitly)
```
[Answer]
# Python 3.5.1, ~~153~~ ~~147~~ 141 ~~124~~ Bytes
```
*s,=input().replace('[?]','*');print(*['aA'[i<1or s[i-2]in'.?!']+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*' else c for i,c in enumerate(s)],sep='')
```
Input :
`[?] apple [?] day keeps the doctor away. [?] lie.`
Output :
`An apple a day keeps the doctor away. A lie.`
123 Bytes version - This does not handle capitalization rule.
```
s=list(input().replace('[?]','*'));print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='')
```
[Try it online!](https://tio.run/##HY29DoIwFIVf5TrdFpBEHZUQBgcnJyfSoSmXcGMtDS0xPH0tbiff@fNbnGZ3SakIVcPOr1HIeiFvtSGBfauwwgLl1S/soih61B32fDvNC4Sej2fFDuv2gKpEh4XIrNwZoCae1@7@eL5Q8gimafIOkA0EBsZc58pADpJbP7ToSCJIVQXyDaJMKT@D9t4S7GrQG7yJfIA4EQyziXlAf/VW/23LVP8A "Python 3 ‚Äì Try It Online")
[Answer]
# C#, ~~204~~ 235 bytes
```
string n(string b){for(int i=0;i<b.Length;i++){if(b[i]=='['){var r="a";r=i==0||b[i-2]=='.'?"A":r;r=System.Text.RegularExpressions.Regex.IsMatch(b[i+4].ToString(),@"[aeiouAEIOU]")?r+"n":r;b=b.Insert(i+3,r);}}return b.Replace("[?]","");}
```
Ungolfed full program:
```
using System;
class a
{
    static void Main()
    {
        string s = Console.ReadLine();
        a c = new a();
        Console.WriteLine(c.n(s));
    }
    string n(string b)
    {
        for (int i = 0; i < b.Length; i++)
        {
            if (b[i] == '[')
            {
                var r = "a";
                r = i == 0 || b[i - 2] == '.' ? "A" : r;
                r = System.Text.RegularExpressions.Regex.IsMatch(b[i + 4].ToString(), @"[aeiouAEIOU]") ? r + "n" : r;
                b = b.Insert(i + 3, r);
            }
        }
        return b.Replace("[?]", "");
    }
}
```
I'm sure this could be improved, especially the Regex part, but can't think of anything right now.
[Answer]
# Java 7, ~~239~~ ~~214~~ 213 bytes
```
String c(String s){String x[]=s.split("\\[\\?\\]"),r="";int i=0,l=x.length-1;for(;i<l;r+=x[i]+(x[i].length()<1|x[i].matches(".+[.!?] $")?65:'a')+("aeiouAEIOU".contains(x[++i].charAt(1)+"")?"n":""));return r+x[l];}
```
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/iwgwyr)
```
class M{
  static String c(String s){
    String x[] = s.split("\\[\\?\\]"),
           r = "";
    int i = 0,
        l = x.length - 1;
    for (; i < l; r += x[i]
                     + (x[i].length() < 1 | x[i].matches(".+[.!?] $") 
                        ? 65
                        : 'a')
                     + ("aeiouAEIOU".contains(x[++i].charAt(1)+"")
                        ? "n"
                        : ""));
    return r + x[l];
  }
  public static void main(String[] a){
    System.out.println(c("Hello, this is [?] world!"));
    System.out.println(c("How about we build [?] big building. It will have [?] orange banana hanging out of [?] window."));
    System.out.println(c("[?] giant en le sky."));
    System.out.println(c("[?] yarn ball? [?] big one!"));
    System.out.println(c("[?] hour ago I met [?] European. "));
    System.out.println(c("Hey sir [Richard], how 'bout [?] cat?"));
    System.out.println(c("[?] dog is barking. [?] cat is scared!"));
  }
}
```
**Output:**
```
Hello, this is a world!
How about we build a big building. It will have an orange banana hanging out of a window.
A giant en le sky.
A yarn ball? A big one!
A hour ago I met an European. 
Hey sir [Richard], how 'bout a cat?
A dog is barking. A cat is scared!
```
[Answer]
## Racket 451 bytes (without regex)
It is obviously a long answer but it replaces a and an with capitalization also: 
```
(define(lc sl item)(ormap(lambda(x)(equal? item x))sl))
(define(lr l i)(list-ref l i))(define(f str)(define sl(string-split str))
(for((i(length sl))#:when(equal?(lr sl i)"[?]"))(define o(if(lc(string->list"aeiouAEIOU")
(string-ref(lr sl(add1 i))0))#t #f))(define p(if(or(= i 0)(lc(string->list".!?")
(let((pr(lr sl(sub1 i))))(string-ref pr(sub1(string-length pr))))))#t #f))
(set! sl(list-set sl i(if o(if p"An""an")(if p"A""a")))))(string-join sl))
```
Testing:
```
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")
```
Output:
```
"A giant en le a sky."
"A yarn ball?"
"A hour ago I met an European."
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"
```
Detailed version: 
```
(define(contains sl item)
  (ormap(lambda(x)(equal? item x))sl))
(define(lr l i)
  (list-ref l i))
(define(f str)
  (define sl(string-split str))
  (for((i(length sl))#:when(equal?(lr sl i)"[?]"))
    (define an   ; a or an
      (if(contains(string->list "aeiouAEIOU")
                  (string-ref(lr sl(add1 i))0))
         #t #f ))
    (define cap   ; capital or not
      (if(or(= i 0)(contains(string->list ".!?")
                            (let ((prev (lr sl(sub1 i)))) (string-ref prev
                                       (sub1(string-length prev))))))
         #t #f))
    (set! sl(list-set sl i (if an (if cap "An" "an" )
                                 (if cap "A" "a")))))
  (string-join sl))
```
[Answer]
# [J](http://jsoftware.com/), 113 bytes
```
[:;:inv 3(0 2&{(((('aA'{~[)<@,'n'#~])~('.?!'e.~{:))~('AEIOUaeiou'e.~{.))&>/@[^:(<@'[?]'=])1{])\' 'cut' . '([,~,)]
```
[Try it online!](https://tio.run/##fZFta8IwFIW/@yuOG3gbqN3bt06nMhwTBgNhn7oOosY2W5aM2lpE6F93STdfNsG@QHvvc885Sd43ZwHN0Q1B8HGJ0L7tAPfjp4dNFN6GUi9x413iurX27EV8QOsqYp2@T5rOq5hVHgW9JomgWofM/Q2Go@cXLqQp6mLAWOvuoh@9hV6nT1Evpm7MrtYxeyXQtMgJAciL/Mpn8YY1xDQ1oEehlPGRp3IB@3CUJlOzJqEdYn7UtqJboLEVMCX4xBQ5SoFJIdXMikxk8vMtdRJgZHtSKaR8KcA1TMZ1YmGu7W2rOrEYnISZuwRSz0wZ7CIcG7gYJyxc@6RHvYxfl@06Bkgk1zmEhhJYfKx2ARx91NuPrXimrY9SPQzqVEaL5uHsAbANXiN7idQUGXhiMMKnyN0WDYvMfAmu/4T4h7nSntudh1hhITNEYzlNeTaLfTtXgqjeQo4pz3v70z3FOv2abmy@AQ "J ‚Äì Try It Online")
Shame, shame!
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~66~~ 60 bytes
```
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])
a$.2*n$1
(^|[.?!] )a
$1A
```
[Try it online.](https://tio.run/##PY/BToRADIbvPEU3wRXMSoIvMPFgZK9eBzZblnFoHFszDBKM744DJKY99O/3t029CcRYLnfZ63Wha61rVTcZZBoNydioXOPjz/GoL7vOE0yLpwdOyyS7/OpCHRrIMUnL52WpjHNygtDTADG1amAS77pDUskE2MoYYDLQjuS6jbZkd0VsCzhHSs5Bj99mw@KRbfQjx4htttEH6xZ537cTdzIVyVpbQg5gGJyB4WPemzN6jvPOqf97wuawsV5GD2gFzvBpwsZfRi9fBrlIKjPDQB70G9169F1ziv4J7rcfVusNg/oD)
**Explanation:**
Do a case-insensitive search for `[?]`  followed by a vowel or consonant, where the optional vowel is saved in capture group 2, and the entire match in capture group 1:
```
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])
```
Replace this with an `a`, followed by the length of the second group amount of `n` (so either 0 or 1 `n`), followed by the letter(s) of capture group 1:
```
a$.2*n$1
```
Then match an `a` at either the start of the string, or after either of `.?!` plus a space:
```
(^|[.?!] )a
```
And uppercase that A, without removing the other characters of capture group 1:
```
$1A
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 154 bytes
```
s->{String v="(?= [aeiou])",q="(?i)\\[\\?]",b="(?<=^|[?.!] )";return s.replaceAll(b+q+v,"An").replaceAll(q+v,"an").replaceAll(b+q,"A").replaceAll(q,"a");}
```
[Try it online!](https://tio.run/##lVLNbqMwEL7nKSa@LGypXyBNUQ@V2kNVaas9EVYawCVOjE1tA0LdPHt2DGq06u6hGGQ0358Gjw/Y4/WhOp5l0xrr4UA177xU/Ptm9Q/22unSS6P/SzpvBTaBKhU6B08o9ep9BbTarlCyBOfR06c3soKG2OjFW6nrLAe0tYsn6WwI66dGOz63wqI39maW3oKF7dld377PNfRbFqVbyFBI0@UxS94CIOPdLtvt0pwlRahvtr9@Zylf5xCzjRW@sxoct6JVWIo7paLi6u2qT9idZvHf8ATiJ5C0pPwkJBmLN6fzR/Oby2@8jM6LhpvO85Za9kpHlmPbqjFiWZrDA9oKPLojZ3H8dds9unGh7UGMKZCXh20dtgVWpUwCfi8d0BsaGIxV1frrCWYALIiCQUDRSVVNKYWs54qGyeGRWKkU7LEXE20s6pr0qOkhWNdh6CHFvM5dSF2ZYdnR1RK1B6FBCXDHcZl5RLo7BSqVXvo3WqwXZexNZwFrA4/QCD/l3HfWtAI1hyXjBCctZD9kuadLlCcUPMC36ZBDZok@vaSdVqfzHw "Java (JDK) ‚Äì Try It Online")
### Explanation:
```
s->{
    String v="(?= [aeiou])",          // matches being followed by a vowel
    q="(?i)\\[\\?]",                  // matches being a [?]
    b="(?<=^|[?.!] )";                // matches being preceded by a sentence beginning
    return s.replaceAll(b+q+v,"An")   // if beginning [?] vowel, you need "An"
        .replaceAll(q+v,"an")         // if           [?] vowel, you need "an"
        .replaceAll(b+q,"A")          // if beginning [?]      , you need "A"
        .replaceAll(q,"a");}          // if           [?]      , you need "a"
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~225~~ ~~207~~ ~~202~~ 201 bytes
Thanks to ceilingcat for -24 bytes
```
#define P strcpy(f+d,index("!?.",i[c-2])+!c?
c;d;v(i,g,f)char*i,*g,*f;{for(d=0;i[c];c++,d++)strcmp("[?]",memcpy(g,i+c,3))?f[d]=i[c]:(index("aeiouAEIOU",i[c+4])?P"An ":"an "),d++:P"A ":"a "),d++,c+=3);}
```
[Try it online!](https://tio.run/##TY87b8IwFIVn@BXGXez4glBhASuKGDp0KkunKIPxI7WUlxwDRYjfntoJrerBOj7f1TnXcllKOQwvShvbaHREvXeyuxHDFNhG6W@CF9kKg83l8rWgbCGzueSKX4iFEgyVX8IlFpISEsPvpnVEpWsepgsuGQPFGI2JdUdwnhUYal3H@BIsk7ChNDO5KtI4vyfPPqFtez68vX98jrVsW9DsiA8Nwnsswk1j6j44o/F8g2TphvLHYBuPamEbQu/zWdwOCefyIo31SHRdpZHtkRZeN@h0Q9GV7XU1Cddekan0FYWUdrSs1CftyhXmU1ridd2ltaiqVpIt5XP0PCN02v@y3W73j4Zv99qTwGENE5p1Z9@TsFzUlyggZkOY@aOTfgw/ "C (gcc) ‚Äì Try It Online")
[Answer]
# Groovy, ~~73~~ 162 bytes
```
def a(s){s.replaceAll(/(?i)(?:(.)?( )?)\[\?\] (.)/){r->"${r[1]?:''}${r[2]?:''}${'.?!'.contains(r[1]?:'.')?'A':'a'}${'aAeEiIoOuU'.contains(r[3])?'n':''} ${r[3]}"}}
```
*edit: damn, the capitalization totally complicated everything here*
[Answer]
# C# 209 bytes
`string A(string b){var s=b.Split(new[]{"[?]"},0);return s.Skip(1).Aggregate(s[0],(x,y)=>x+(x==""||(x.Last()==' '&&".?!".Contains(x.Trim().Last()))?"A":"a")+("AEIOUaeiou".Contains(y.Trim().First())?"n":"")+y);}`
Formatted
```
string A(string b)
{
    var s = b.Split(new[] { "[?]" }, 0);
    return s.Skip(1).Aggregate(s[0], (x, y) => x + (x == "" || (x.Last() == ' ' && ".?!".Contains(x.Trim().Last())) ? "A" : "a") + ("AEIOUaeiou".Contains(y.Trim().First()) ? "n" : "") + y);
}
```
[Answer]
# [Perl 6](https://perl6.org), 78 bytes
```
{S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{$0 xx?$0}{<a A>[?$0]}{'n'x?~$1} $1/}
```
## Explanation:
```
{
  S
    :ignorecase
    :global
  /
    ( # $0
    | ^             # beginning of line
    | <[.?!]> ' '   # or one of [.?!] followed by a space
    ) ?             # optionally ( $0 will be Nil if it doesn't match )
    '[?] '          # the thing to replace ( with trailing space )
    ( # $1
      <[aeiou]> ?   # optional vowel ( $1 will be '' if it doesn't match )
    )
  /{
    $0 xx ?$0      # list repeat $0 if $0
                   # ( so that it doesn't produce an error )
  }{
    < a A >[ ?$0 ] # 'A' if $0 exists, otherwise 'a'
  }{
    'n' x ?~$1     # 'n' if $1 isn't empty
                   # ÔΩ¢~ÔΩ£ turns the Match into a Str
                   # ÔΩ¢?ÔΩ£ turns that Str into a Bool
                   # ÔΩ¢xÔΩ£ string repeat the left side by the amount of the right
  # a space and the vowel we may have borrowed
  } $1/
}
```
## Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &code = {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{<a A>[?$0]~('n'x?~$1)} $1/}
my @tests = (
  'Hello, this is [?] world!'
  => 'Hello, this is a world!',
  'How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.'
  => 'How about we build a big building. It will have an orange banana hanging out of a window.',
  '[?] giant en le sky.'
  => 'A giant en le sky.',
  '[?] yarn ball?'
  => 'A yarn ball?',
  '[?] hour ago I met [?] European.'
  => 'A hour ago I met an European.',
  "Hey sir [Richard], how 'bout [?] cat?"
  => "Hey sir [Richard], how 'bout a cat?",
);
plan +@tests;
for @tests -> $_ ( :key($input), :value($expected) ) {
  is code($input), $expected, $input.perl;
}
```
```
1..6
ok 1 - "Hello, this is a world!"
ok 2 - "How about we build a big building. It will have an orange banana hanging out of a window."
ok 3 - "A giant en le sky."
ok 4 - "A yarn ball?"
ok 5 - "A hour ago I met an European."
ok 6 - "Hey sir [Richard], how 'bout a cat?"
```
[Answer]
# Lua, 131 Bytes.
```
function(s)return s:gsub("%[%?%](%s*.)",function(a)return"a"..(a:find("[AEIOUaeiou]")and"n"or"")..a end):gsub("^.",string.upper)end
```
Although lua is a terrible Language for golfing, I feel I've done pretty well.
[Answer]
## [Pip](http://github.com/dloscutoff/pip), ~~62~~ ~~55~~ ~~54~~ 50 bytes
Takes the string as a command-line argument.
```
aR-`([^.?!] )?\[\?]( [^aeiou])?`{[b"aA"@!b'nX!cc]}
```
[Try it online!](http://pip.tryitonline.net/#code=YVItYChbXi4_IV0gKT9cW1w_XSggW15hZWlvdV0pP2B7W2IiYUEiQCFiJ25YIWNjXX0&input=&args=Wz9dIGhvdXIgYWdvIEkgbWV0IFs_XSBFdXJvcGVhbiEgWz9dIG1hbi4gWz9dIElyaXNobWFuLg)
Explanation:
```
a                                                   Cmdline argument
 R                                                  Replace...
  -`                           `                    The following regex (case-insensitive):
    ([^.?!] )?                                      Group 1: not end-of-sentence (nil if it doesn't match)
              \[\?]                                 [?]
                   ( [^aeiou])?                     Group 2: not vowel (nil if there is a vowel)
                                {                }  ... with this callback function (b = grp1, c = grp2):
                                 [              ]   List (concatenated when cast to string) of:
                                  b                 Group 1
                                   "aA"@!b          "a" if group 1 matched, else "A"
                                          'nX!c     "n" if group 2 didn't match, else ""
                                               c    Group 2
```
[Answer]
## Racket (with regex) 228 bytes
```
(define(r a b c)(regexp-replace* a b c))
(define(f s)
(set! s(r #rx"[a-zA-Z ]\\[\\?\\] (?=[aeiouAEIOU])"s" an "))
(set! s(r #rx"[a-zA-Z ]\\[\\?\\]"s" a"))
(set! s(r #rx"\\[\\?\\] (?=[aeiouAEIOU])"s"An "))
(r #rx"\\[\\?\\]"s"A"))
```
Testing: 
```
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] apple?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")
```
Output:
```
"A giant en le a sky."
"A yarn ball?"
"An apple?"
"A hour ago I met an European. "
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~104~~ 103 bytes
-1 bytes, unescaped `]`
```
lambda s:r('(^|[.?!] )a',r'\1A',r('a( [aeiouAEIOU])',r'an\1',r('\[\?]','a',s)));from re import sub as r
```
[Try it online!](https://tio.run/##fZFRa4MwFIXf@ytu@6IBKZS9bQzxobA@DQZ7UgfXGWNYvJEYJ8L@u4u2tOpGURBzvnvOSVL3ttT0MBTPyaCwynKE5tH4nv/xE@/DbQoMvcB4ySFyH99DH2LkUrfR8fT6nrJRQ0oOk5jESZh6gecmGsbYU2F0BYaDrGptLDRtBtiAGWojyfqFv3vhSukAbCkbcG8cptBpo/LtjrHNmVozeCU2m5uP7gAz3VroOGStVPnklUlx/pMk9nByqlQKSvzmk6wNknA8knvcMgnHweiii3MXSbnu9vMyf4PwXgzS/RS8Zcy2M2YLiWSBEygOzVc/LxH9I66mezTkIpUKrwehiW8XJjMmmhErp1K3BlBoOEHF7eR2bI2uOdKy0wp0O59x87viPTTSQPwmP0s0eRq40Q686VRH@0@04eL@7/B4oVeluRCLcnRZGX4B "Python 3 ‚Äì Try It Online")
Starts by replacing all occurences of `[?]` with `a`,  
Then replaces all `a` followed by a vowel, with `an`.  
Then replaces all `a` at the start of input or a sentence with `A`.
Assumes that `[?]` will never be touching another word, and that lower-case `a` should never begin a sentence.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 124 bytes
inspired by Avi's [answer for Java](https://codegolf.stackexchange.com/a/193803/80745).
```
$args-replace(($b='(?<=^|[?.!] )')+($q='\[\?]')+($v='(?= [aeiou])')),'An'-replace"$q$v",'an'-replace"$b$q",'A'-replace$q,'a'
```
[Try it online!](https://tio.run/##fZPBbqMwEIbvPMUkcmvQ0jxAtYjmsNL2ulfKVgNMwVrXDgZCo7bPnh1IkxAqxXDx72/@f2zMxvbkmoq03osXiOB9L9CVzZ2jjcacfF9kkfTjn9HfjyReLVIIZPDDF3Ukn5KnOB0n24GIIEFStksZCEK5NvLosRS12C5DiVMpEzVL65Miagbk/tPzHnwPeIQ@gPzNfdkQ2ko1wG8Sp9Bbp4uFDEdoGHMIj0gw8bE9YGa7FnqCrFO6GL0yVR5mypQreORVpTVUuKVx2To0JfNo@GHZlMzB4GJfDr0oU9h@ddHM9yS8loPmegyeQibbGbJLhaYFMqAJmn@7iybW31dn1Tt0hhO1jk8HYQ0tLk0m0PqMzJwq2znA0sIjvFI7uv3qnN0QmllPM5J3fgan34p20CgHyR@VV@iKNOTKHqQcT3Xwz7GNLy/AtQo88IEXwAfcwPtYJ5oQBL1tKG@p4Gsvng@yo6bTLQu3/DeIZhSXwv/S73KqT1XB/RFfep/7/w "PowerShell ‚Äì Try It Online")
]