text:
Evaluate a chain of inequalities
Write code to evaluate whether a chain of inequalities is true or false. An example input is the string
3<=4!=9>3==3
This is true because each of its components is true:
(3<=4) and (4!=9) and (9>3) and (3==3)
Input:
A string that represents a chain of one or more inequalities. The allowed comparison operators are
==   equals
!=   does not equal
>    is greater than
>=   is greater than or equal to
<    is less than
<=   is less than or equal to

The allowed numbers are single-digit numbers 0 through 9. There won't be any spaces, parentheses, or other symbols.
Output:
The correctness of the inequality as a consistent Truthy or Falsey value. Consistent means every Truthy output is the same and every Falsey output is the same.
Restriction:
The intent of this challenge is for you to write code that processes the inequalities, rather than have them be evaluating them as code, even for a single inequality in the chain. As such, methods like Python's eval and exec that evaluate or execute code are banned. So are functions which look up a method or operator given its name as a string. Nor is it allowed to launching processes or programs to do the evaluation for you.
Test cases:
3<=4!=9>3==3
True

3<=4!=4
False

5>5
False

8==8<9>0!=2>=1
True

Can we accept input with Unicode inequality signs like ≤ and ≥ instead of <= and >=?

@FUZxxl You can't.

Ruby, 71 + 1 = 72
With command-line flag -n, run
p (0..99).none?{|i|~/#{a=i%10}(#{%w/!=|. <?=* >?=*/[a<=>b=i/10]})#{b}/}

Generates all possible failing regular expressions, and checks whether the input string matches any of them. Outputs true if none do, else false. Takes input via STDIN, separated by newlines.
Tricks:

We get all possible pairs of digits by looping from 0 to 99 and extracting the 10s and 1s digits.
The only actual comparison we do is a<=>b, which returns -1,0,or 1 for less than, equal to, or greater. These all slice to different elements of a three-string array, finding the regular expression for comparisons that don't match.

What a clever strategy!

Perl, 82
$_=<>;($'<=>$&)-61+ord$1&&($2&&$&==$')^('$'lt$1)&&die"\n"while/\d(.)(=?)/g;print 1

Prints 1 when true and a blank line when false, since the empty string is Perl's main falsey value.
The while loop goes over the string matching the regex \d(.)(=?). Then the variables $1 and $2 correspond to the characters of the operator, and the special variables $& and $' will behave as the two operands in a numerical context. The operands are compared with <=> and the result matched against the first character of the operator. Then equality and inequality is dealt with specially.

JavaScript (ES6) 110 116
Straightforward:scan string, c is current digit, l is last digit, o is operator.
F=x=>(l='',[for(c of x)10-c?(v=!l||v&&(o<'<'?l!=c:(o[1]&&c==l)||(o<'='?l<c:o<'>'?c==l:l>c)),l=c,o=''):o+=c],v)

Test In Firefox / FireBug console
;['3<=4!=9>3==3','3<=4!=4','5>5','8==8<9>0!=2>=1']
.forEach(s=>console.log(s,F(s)))

3<=4!=9>3==3 true
3<=4!=4 false
5>5 false
8==8<9>0!=2>=1 true

CJam, 60 bytes
This code seems a bit ugly and potentially not fully optimized, but it's the best I've got so far.
Try it online.
q_A,sSer_S%@@-(])1\@z{~:X\:^i['=")<"P"(>"P'<'^'>PPP]=~e&X}/;

Explanation
q               "Read the input";
_A,sSer         "Copy the input and replace each digit with a space";
_S%             "Split around spaces to obtain the operation list";
@@-             "Remove operations from the input to obtain the operand list";
(])1\@z         "Remove the first operand from the list to be the initial left
                 operand, initialize the result to 1 (true), and pair up the
                 operations and remaining operands";
{               "For each operation-operand pair:";
  ~:X             "Let the operand be the right operand of this operation";
  \:^i            "Hash the operation (bitwise XOR of all characters)";
  [               "Begin cases:";
    '=              " 0: Equals";
    ")<"            " 1: Less than or equal to";
    P               " 2: (Invalid)";
    "(>"            " 3: Greater than or equal to";
    P               " 4: (Invalid)";
    '<              " 5: Less than";
    '^              " 6: Bitwise XOR (stand-in for not equal to)";
    '>              " 7: Greater than";
    P               " 8: (Invalid)";
    P               " 9: (Invalid)";
    P               "10: (Invalid)";
  ]=~             "Execute the case selected by the operation hash modulo 11";
  e&              "Compute the logical AND of the result and the value produced
                   by this operation to be the new result";
  X               "Let the right operand be the new left operand";
}/              "End for each";
;               "Clean up and implicitly print result";

Haskell, 156 bytes
r a=read[a]::Int
l"!"=(/=)
l"="=(==)
l">"=(>=)
l"<"=(<=)
k">"=(>)
k"<"=(<)
[]#_=1<2
(a:'=':b:c)#i=l[a]i(r b)&&c#r b
(a:b:c)#i=k[a]i(r b)&&c#r b
f(h:t)=t#r h

Usage example:
f "3<=4!=9>3==3"        -> True
f "3<=4!=4"             -> False
f "5>5"                 -> False
f "8==8<9>0!=2>=1"      -> True

Ungolfed version:
digitToInt d = read [d] :: Int

lookup2 "!" = (/=)
lookup2 "=" = (==)
lookup2 ">" = (>=)
lookup2 "<" = (<=)

lookup1 ">" = (>)
lookup1 "<" = (<)

eval []              _ = True
eval (op:'=':d:rest) i = lookup2 [op] i (digitToInt d) && eval rest (digitToInt d)
eval (op:d:rest)     i = lookup1 [op] i (digitToInt d) && eval rest (digitToInt d)

evalChain (hd:rest) = eval rest (digitToInt hd)

eval takes two arguments: the string to parse (starting always with a comparison operator) and a number i which is the left argument for comparison (and was the right argument in the previous round). The operator is returned by lookup2 if it's a two character operator (check only 1st char, because 2nd is always =) and by lookup1 if it's just a single character. eval calls itself recursively and combines all return values with logical and &&.

Common Lisp - 300 185  169 165
(lambda(s)(loop for(a o b)on(mapcar'read-from-string(cdr(ppcre:split"([0-9]+)"s :with-registers-p t)))by #'cddr always(if o(funcall(case o(=='=)(!='/=)(t o))a b)t)))

Example
(mapcar (lambda(s) ...)
       '("2<=3<=6>2<10!=3"
         "3<=4!=9>3==3"
         "3<=4!=4"
         "5>5"
         "8==8<9>0!=2>=1"))
=> (T T NIL NIL T)

Explanation
(lambda (s)
  (loop for (a o b) on (mapcar
                        'read-from-string
                        (cdr
                         (cl-ppcre:split "([0-9]+)" s
                                         :with-registers-p t))) by #'cddr
        always (if o
                   (funcall (case o
                                  (== '=)
                                  (!= '/=)
                                  (t o))
                            a b)
                   t)))

ppcre:split splits on digits; for example:
(ppcre:split "([0-9]+)" "2<=3<=6>2<10!=3" :with-registers-p t)
=> ("" "2" "<=" "3" "<=" "6" ">" "2" "<" "10" "!=" "3")

Notice the first empty string, which is discarded using cdr
Mapping read-from-string to this list calls the read function for each strings, which returns symbols and numbers.
loop for (a op b) on '(3 < 5 > 2) by #'cddr iterates over the list by a step of 2 and thus binds a, op and b as follows, for each successive pass.
a  op  b
----------
3  <    5
5  >    2
2  nil  nil

always checks whether the next expression is always true: either the operator is nil (see above) or the result of the comparison holds (see below).
the case selects a Common-Lisp comparison function, according to the symbol previously read; since some operators are identical in Lisp and the given language  we can simply return o in the default case.

Python 2, 95 102
t=1
n=o=3
for c in map(ord,raw_input()):
 o+=c
 if 47<c<58:t&=627>>(o-c+3*cmp(n,c))%13;n=c;o=0
print t

The loop is a straightforward pass through the string one character at a time. The t&=... part is where the magic happens. Basically, I hash the operator together with the value of cmp(lhs,rhs) (-1, 0, or 1 depending on if lhs is less, equal, or greater than rhs). The result is a key into a lookup table that gives 0 or 1 depending on whether the numbers compare properly given that operator.  What lookup table, you ask? It's the number 627 = 0001001110011 in binary.  Bitwise operators do the rest.
This works on the four given test cases; let me know if you find an error for another case.  I haven't tested it very rigorously.

You need to take in a as input.

@xnor Whoops. Corrected.

05AB1E, 37 bytes
þS¡¦Uþü.S"=<!>"2×Sć«'<š'>ª3ôÀsèXδåÅ\P

Try it online or verify all test cases.
Explanation:
þ         # Only leave the digits of the (implicit) input-string
          #  i.e. "3<=4!=9>3==3" → "34933"
 S        # Convert it to a list of digits
          #  → [3,4,9,3,3]
  ¡       # Split the (implicit) input-string by those, to have a list of the comparisons
          #  → ["","<=","!=",">","==",""]
   ¦      # Remove the first item (which is an empty string)
          #  → ["<=","!=",">","==",""]
          # (it also contains a trailing empty string, but we'll ignore that)
    U     # Pop and store it in variable `X`
þ         # Only leave the digits of the (implicit) input-string again
 ü        # For each overlapping pair of digits:
  .S      #  Compare them: -1 if a<b; 0 if a==b; 1 if a>b
          #   → [[3,4],[4,9],[9,3],[3,3]] → [-1,-1,1,0]
"=<!>"    # Push string "=<!>"
      2×  # Double it to "=<!>=<!>"
        S # Convert it to a list of characters: ["=","<","!",">","=","<","!",">"]
ć         # Extract the head: pop and push remainder-list and head separately
 «        # Append this "=" to each: ["<=","!=",">=","==","<=","!=",">="]
  '<š'>ª  # Prepend a "<" and append a ">": ["<","<=","!=",">=","==","<=","!=",">=",">"]
3ô        # Split it into parts of size 3: [["<","<=","!="],[">=","==","<="],["!=",">=",">"]]
  À       # Rotate this list once left: [[">=","==","<="],["!=",">=",">"],["<","<=","!="]]
   sè     # Index the digit-comparisons into it (where the -1 indexes into the last item)
          #  → [["<","<=","!="],["<","<=","!="],["!=",">=",">"],[">=","==","<="]]
X         # Push the input-comparisons from variable `X` again
 δ        # Apply double-vectorized:
  å       #  Check if the current comparison is in the current list
          #   → [[1,1,0,0,0],[1,1,0,0,0],[0,1,1,0,0],[1,0,0,1,0]]
   Å\     # Leave the main diagonal of these double-vectorized checks
          #  → [1,1,1,1]
     P    # And check if all are truthy by taking their product
          #  → 1
          # (after which the result is output implicitly)

Javascript 101 bytes
a different approach from the js solution posted here

F=(s,i=0,l=o="")=>[...s].every(c=>c>=0?[l^c,l==c,,l<c,l>c,l<=c,,l>=c]["!==<><=>=".search(o,l=c,o="")]:o+=c,l=o="")

console.log(F("3<=4!=9>3==3")==true)
console.log(F("3<=4!=4")==false)
console.log(F("5>5")==false)
console.log(F("8==8<9>0!=2>=1")==true)

Java 8, 283 270 bytes
s->{String[]a=s.split("\\d"),b=s.split("\\D+");int i=0,r=1,x,y;for(;i<a.length-1;y=new Byte(b[++i]),r-=a[i].equals("==")&x!=y|a[i].equals("!=")&x==y|a[i].equals(">")&x<=y|a[i].equals(">=")&x<y|a[i].equals("<")&x>=y|a[i].equals("<=")&x>y?1:0)x=new Byte(b[i]);return r>0;}

-13 bytes thanks to @ceilingcat.
Explanation:
Try it here.
s->{                             // Method with String parameter and boolean return-type
  String[]a=s.split("\\d"),      //  All the inequalities
          b=s.split("\\D+");     //  All the digits
  int i=0,                       //  Index-integer (starting at 0)
      r=1,                       //  Flag integer for the result, starting at 1
      x,y;                       //  Temp integer `x` and `y`
  for(;i<a.length-1              //  Loop `i` in the range [0, length]:
      ;                          //    After every iteration:
       y=new Byte(b[++i]),       //     Convert the `i+1`'th digit from String to integer,
                                 //     and store it in `y`
       r-=                       //     Decrease the result by:
          a[i].equals("==")&x!=y //      If "==" and `x` and `y` are not equal
          |a[i].equals("!=")&x==y//      or if "!=" and `x` and `y` are equal
          |a[i].equals(">")&x<=y //      or if ">" and `x` is smaller than or equal to `y`
          |a[i].equals(">=")&x<y //      or if ">=" and `x` is smaller than `y`
          |a[i].equals("<")&x>=y //      or if "<" and `x` is larger than o equal to `y`
          |a[i].equals("<=")&x>y //      or if "<=" and `x` is larger than `y`:
           1                     //       Decrease the result by 1
          :0;                    //      Else: keep it the same by decreasing with 0
    x=new Byte(b[i]);            //   Convert the `i`'th digit from String to integer,
                                 //   and store it in `x`
  return r>0;}                   //  Return whether the result is still 1


text:
ICS Maritime Flag alphabet
The International Code of Signals flag alphabet  is used by ships for communication, particularly for static signals.
Your challenge is to write a program or function that will take a string from STDIN or as an argument, and display the corresponding text in the ICS flag alphabet. If your language does not display to the screen, saving to a file is acceptable.
Your program or function shall support letters A-Z in upper and lower case, plus Space and Newline. Behaviour with other characters is undefined.
The display shall be large enough to display capable of displaying at least 8 flags horizontally and 6 flags vertically. Behaviour is undefined if the right hand edge is reached before a newline is received, or if the message is too long to fit the display vertically.
The flag alphabet is as shown below (Roman letters are for reference only, they are not required in the output.)

Dimensions
There is no universally agreed standard for the dimensions of these flags, so for the purpose of this challenge the following shall apply:
Flags shall be 60x60 pixels, with a 30 pixel gap between them both horizontally and vertically.
The swallowtail cut on A and B shall be 15 pixels deep.
All other lines shall be horizontal, vertical, or at 45 degrees.
The features shall be located by dividing the flag into an imaginary NxN grid of side 3,4,5 or 6 squares. Refer to the above image, but for further clarification:
A,E,H,K, L and U are based on a 2x2 grid : width of each colour zone shall be 30pixels. Also the points of the diamond in F shall be halfway along each side of the flag.
J and T are based on a 3x3 grid: each band shall be 20 pixels.
P,N and S are based on a 4x4 grid. Also the diagonal lines of Y shall split the edges of the flag into 4.
C,D,R and X shall be based on a 5x5 grid. Bands and arms of crosses shall be 12 pixels wide.
G,W,M,V are based on a 6x6 grid. Bands of G and borders of W shall be 10 pixels wide.
Arms of crosses on M and V shall cover the first and last 10 pixels of each edge of the flag, leaving triangle zones measuring 40 pixels along the long edge.
The circle of I shall be in the centre of the flag and have diameter 30 pixels.
An error of +/-1 pixel from the above text is permitted. If your language only supports scalable graphics, you may interpret "pixels" to mean "units."
Colours
Colours shall be red, white, blue, yellow and black as defined by your language or its documentation. If your language does not define colours, you may use the following:
Red FF0000,
White FFFFFF,
Blue 0000FF,
Yellow FFFF00,
Black 0000000.
Background shall be grey (r,g and b channels equal, between 25% and 75% intensity.)
Scoring /Loopholes
This is codegolf. Shortest code in bytes wins.
Standard loopholes are disallowed.
No builtin or library functions for displaying flags may be used. Output shall be non-text (and in particular, unicode characters shall not be used to build up the flag shape.)
Example
JFK got
my VHS
PC
and XLR
web quiz

should produce the following

I'm not entirely sure what you mean by "The display shall be large enough to display at least 8 flags horizontally and 6 flags vertically", especially given that your test case shows an output which is only 5 flags tall. Is it just that answers must handle messages up to those dimensions and are not required to handle larger ones, or do you intend to require that all lines should be padded to at least 8 chars and all messages to at least 6 lines?

@PeterTaylor If your program or language is intelligent enough to resize the display according to the output, there is no need to pad the display to 8x6 if the output is smaller. The output shall be have a grey background and be rectangular (all lines padded to at least the length of the longest line.)

CJam, 464 bytes
You thought CJam didn't have image manipulation functions? Well, you thought right! But I wasn't going to let that stop me.
"P3
690 690 4
"3a3*a690_@*a*qeuN/{0:U;{_'C<.5*:N;i[{XY+Z<[E8][9C]?XY<=}WWWW{XH<9F?}C{YC/[9FCF]=}{YC/3&9E?}{YH<9F?}{X29.5:R-zYR-z+H>FC?}{XA/1&9E?}{XH<FC?}{XR-_*YR-_*+F_*>E8?}{YK/(9F?}{XH<E9?}{XH<YH<^8E?}{XY+Z-A/XY-A/e&9F?}{XF/YF/^1&F9?}{XY<EC?}{XH-F/YH-F/|9F?}E{XHm6/YHm6/e&CE?}{XH-F/YH-F/|F9?}{XK/[CF9]=}{XH<YH<^FC?}{XY+Z-A/XY-A/e&FC?}{XR-zYR-ze>iA/[CF9]=}{XHm6/YHm6/e&F9?}{XY+F/1&CE?}]=:P~!!{60:Z{Z30:HYH-z-N*-{YV+_2$=XU+P2b1>4f*tt}fX}fY}*U90+:U;}/V90+:V;}/`"[]"-

This program outputs the image in the best way CJam can: as text that represents the image when saved as a PPM file. Don't even try running it with the online interpreter, by the way; you'll blow the stack. Run it with the Java interpreter and pipe the output to a file with a command like java -jar cjam-0.6.4.jar flags.cjam > flags.ppm. Once you've provided your input, send an EOF (may need to be immediately after a newline) with ctrl+D on Unix or ctrl+Z on Windows.
Sample
If it's really desired, I can try to paste the original ~3MB image source somewhere. But here's the result opened in GIMP and conerted to a PNG:
ABCDEFG
hijklmn
OPQRSTU
vwxyz z

Explanation
The image header, easily identifiable in the source, consists of the magic number, width, height, and maximum channel value. So the output is a 690*690 image (enough for 8*8 60px flags with 30px of spacing between them) with each R, G, and B value ranging from 0 to 4.
The image data is initialized as a 690*690*3 array filled with 3's, making the whole image light gray. Then the input is read, converted to uppercase, and split into lines. The lines are processed in a loop, incrementing the flag Y coordinate by 90 each iteration, and in each line, each character is processed in a loop, incrementing the flag X coordinate by 90 each iteration. Now the magic begins.
Each character is mapped to a flag's pixel function that, when called, returns the color of the pixel at the position (X, Y) on the flag. This is where most of the hard work went: concisely describing 26 images as mathematical functions. Each of these functions returns a color value from 8-15. This range takes advantage of the fact that, when converted to base 2, the resulting bit array can be interpreted as [1, R, G, B]. The first element can be removed and the rest multiplied by 4 to easily give a pixel value in the desired format that covers all the possible flag colors (as well as green, cyan, and magenta). It also works out nicely that there are one-character variables initialized to 10-15, and since varaibles don't need a space to syntactically separate them, any two colors besides black and blue can be entered next to each other without needing any spacing.
Once the function is retrieved, it's just a matter of iterating over both of X and Y from 0-60, calling the function at each step, and writing the result back to the image data array. An astute observer might notice that the color values returned by each flag function don't allow gray, though. So there's a bit of extra logic to skip spaces. But there are still the swallowtail cuts on 'A' and 'B'. So there's a bit of extra logic there, too. If the character value is less than 'C', a value is set such that the upper bound on the X loop varies correctly with respect to Y and the cut-out areas are never drawn.
Overall, I'm pretty happy with how this came out. It took a lot of work, but it was fun. Some flags don't perfectly match the reference image, but I think I got all the shapes to be within 1px of the target (if any are off by more than that, let me know and I'll fix them). And there's definitely still potential to optimize, as there's a fair amount of redundancy between the 26 flag functions.

Ineresting first attempt, 559 bytes
Altough I never quite finished this, I'll post it too, because it's pretty interesting. Instead of modelling each flag by a function of (X, Y) → color, flags are drawn as a composition of simple shapes. But I was worried about needing to write a substantial amount of rendering code for each different shape. After a lot of pondering, I realized I could render them all, with some clever overlapping and overdrawing, with just one pseudo-shape: all the points within a specified distance of a specified point, where the definition of "distance" is variable. Chessboard distance gives a square, Manhattan distance gives a diamond, and Euclidean distance gives a circle. This meant every shape had the same five parameters (color, distance mode, x, y, and max distance) and I only needed to write one shape data decoder and one rendering function with a small bit of distance mode logic.
"P3
690 690 4
"3a3*a690_@*a*qeuN/{0:U;{_'C<.5*:N;i[[8EX30:Q0Q9X60:ZQQCXQZQ]LLLL[F9TTQQ]Ca[9FTQ42QCTQ54QFTQ66Q9TQ78Q][E9TIQI9T42QI][9FTQZQ][FCXQQQ][E9T40QQET50QQ9TZQQET70QQ9T80QQ][FCTZQQ][E8YQQF][9FTQAQ9TQ9~Q][E9TZQQ][8ETTTQETZZQ][F9XQTK9XZQK9XQZK9XTQK][F4{4{JW^1&6*9+TJ)F*W)F*F}fJ}fW][CEX0ZZ][9FTQQF]Ea[E[TZ]_m*{CT@~24}/][F9TQQF][9FTAQQCT9~QQ][FCTTTQCTZZQ]C9$1>9a/Fa*+[9FTQQKCTQQA]9 6$1>Ca/Fa*+[C7{7\-_1&2*C+X@TT@F*}/]]=_!!{([TQQQ]+\+}*5/{~:R;.5-:H;.5-:G;:M;2b1>4f*:O;Z{ZQWQ-z-N*-{JG-{zM_!+#}:P~WH-PM{+}{e>}?RP<{WV+_2$=JU+Ott}*}fJ}fW}/U90+:U;}/V90+:V;}/`"[]"-

Excellent, this is the kind of creative answer I was looking for. Will try to run it later.

This is quite possibly the longest CJam code I've ever seen. Nice work though, +1.

Again, CJam appears to save the day.

Unfortunately, it's a federal offense to post CJam code longer than 200 bytes. I'm gonna have to take you into custody.

PHP, 811 bytes
function f($s){echo"";$z=split("\n",gzinflate(base64_decode("vVfNasMwDL7vKQK7xlT+iaHQ9LDTLnuIQus6ENhgxS19+kmO0yRrkhbqGIxtyV8sWbIkZ/Prjtm52p9suYbMHqqjPdHMVYfzx/elhBzyNbXtZoXQ7dvm+Q9+dieb7csvZFkJToNlEq6Zqeq6fAcw2arDqCKXUPMCEYQicIc1xmNfUkBDzXgQkpMQ3W0PEGF7fz49dT7IuSCQ1APJ5h9IKAIhdGn1jIHH6oUzvCpZzhtGjoDiePzuzAPJEkG1JPk1uw29G5rC7pxAvAFxuHqd+nQxpCP65S4gR6wzAkphE4rPHfbYaAueky59BrmrZ4wU0Ss8SES/pCNugMduiBSYs25oJTeBSYNMbHO6+bUg22PPhA8E5LCWhT3SFBjEwxaWiOMYD1+FtZSZxateEAZ7pvsEL7w1aQxD3HxLcmayfNA9ZeXzcdteJLm0H5ZITzAwolDkXeGwVAvlSzUOSDDkMRqRxDkuLquVecbKMRKFaESLSYOMg4b6qVHQMnkMns5jyZLBAnksRehirQWrwClEqakDNrqKpjqKpZ8K5rVYTFE56ZmCyT68KinJX+n/puFpyHXg4RRLwg1oW6YipqfimfJTt6/c6XIv6Tnc/HxNXIj+a9nORdwN5Qa3qzvGHw==")));while($c=ord(ucfirst($s))){$s=substr($s,1);echo$c<32?'
':($c^32?$z[$c-64]:$z[0]);}}

The compressed blob contains SVG code for each of the 26 flags. A simple loop then extracts and outputs the SVG image corresponding to each character of the input.
Sample output for "This is\na test":

<svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h30v60h-30z fill=#fff /><path d=M30,0h30v60h-30z fill=#f00 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#ff0 /><path d=M15,30a15,15,0,0,1,30,0a15,15,0,0,1-30,0z fill=#000 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#ff0 /><path d=M15,30a15,15,0,0,1,30,0a15,15,0,0,1-30,0z fill=#000 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg>
<svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h30v60h-30z fill=#00f /><path d=M45,30l15-30h-30v60h30z fill=#fff /></svg><svg width=90 height=90 viewBox=0,0,90,90></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v30h-60z fill=#00f /><path d=M0,30h60v30h-60z fill=#fff /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg>

(You can try it out at ideone, although it won't render the page for you.)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Tips for Regex Golf
Similar to our threads for language-specific golfing tips: what are general tricks to shorten regular expressions?
I can see three uses of regex when it comes to golfing: classic regex golf ("here is a list that should match, and here is a list that should fail"), using regex to solve computational problems and regular expressions used as parts of larger golfed code. Feel free to post tips addressing any or all of these. If your tip is limited to one or more flavours, please state these flavours at the top.
As usual, please stick to one tip (or family of very closely related tips) per answer, so that the most useful tips can rise to the top via voting.

Flagrant self-promotion: what category of regex-use does this fall into? http://codegolf.stackexchange.com/a/37685/8048

@KyleStrand "regular expressions used as parts of larger golfed code."

When not to escape
These rules apply to most flavours, if not all:

] doesn't need escaping when unmatched.
{ and } don't need escaping when they are not part of a repetition, e.g. {a} matches {a} literally. Even if you want to match something like {2}, you only need to escape one of them, e.g. {2\}.

In character classes:

] doesn't need escaping when it's the first character in a character set, e.g. []abc] matches one of ]abc, or when it's the second character after a ^, e.g. [^]] matches anything but ]. (Notable exception: ECMAScript flavour!)
[ doesn't need escaping at all. Together with the above tip, this means you can match both brackets with the horribly counter-intuitive character class [][].
^ doesn't need escaping when it's not the first character in a character set, e.g. [ab^c].
- doesn't need escaping when it's either the first (second after a ^) or last character in a character set, e.g. [-abc], [^-abc] or [abc-].
No other characters need escaping inside a character class, even if they are meta characters outside of character classes (except for backslash \ itself).

Also, in some flavours ^ and $ are matched literally when they are not at the start or end of the regex respectively.
(Thanks to @MartinBüttner for filling in a few details)

Some prefer escaping the actual dot by enclosing it in a character class where it doesn't need escaping (eg. [.]). Escaping it normally would save 1 byte in this case \.

Note that [ must be escaped in Java. Not sure about ICU (used in Android and iOS) or .NET, though.

A simple regular expression to match all printable characters in the ASCII table.
[ -~]

pure awesomeness, all the chars from a standard US keyboard! note: the standard ascii table (not including the extended range 127-255

I use it often, but it is missing a common "regular" character: TAB.  And it assumes you are using LC_ALL="C" (or similar) as some other locales will fail.

Can the hyphen be used like that to specify any range of characters in the ASCII table? Does that work for all flavours of regex?

Know your regex flavours
There are a surprising amount of people who think that regular expressions are essentially language agnostic. However, there are actually quite substantial differences between flavours, and especially for code golf it's good to know a few of them, and their interesting features, so you can pick the best for each task. Here is an overview over several important flavours and what sets them apart from others. (This list can't really be complete, but let me know if I missed something really glaring.)
Perl and PCRE
I'm throwing these into a single pot, as I'm not too familiar with the Perl flavour and they're mostly equivalent (PCRE is for Perl-Compatible Regular Expressions after all). The main advantage of the Perl flavour is that you can actually call Perl code from inside the regex and substitution.

Recursion/subroutines. Probably the most important feature for golfing (which only exists in a couple of flavours).
Conditional patterns (?(group)yes|no).
Supports change of case in the replacement string with \l, \u, \L and \U.
PCRE allows alternation in lookbehinds, where each alternative can have a different (but fixed) length. (Most flavours, including Perl require lookbehinds to have an overall fixed length.)
\G to anchor a match to the end of the previous match.
\K to reset the beginning of the match
PCRE supports both Unicode character properties and scripts.
\Q...\E to escape longer runs of characters. Useful when you're trying to match a string that contains many meta-characters.

.NET
This is probably the most powerful flavour, with only very few shortcomings.

Supports arbitrary-length lookbehinds, which are matched right-to-left.
Has the unique concept of balancing groups - originally designed to match strings with balanced parentheses, they can be used to perform arithmetic and match 2D patterns.
Also supports conditional patterns.
Has concise syntax for character class difference: [\w-[aeiou]]
The normal character classes like \d are Unicode aware.
Supports Unicode categories and blocks.

One important shortcoming in terms of golfing is that it doesn't support possessive quantifiers like some other flavours. Instead of .?+ you'll have to write (?>.?).
Java

Due to a bug (see Appendix) Java supports a limited type of variable-length lookbehind: you can lookbehind all the way to the beginning of the string with .* from where you can now start a lookahead, like (?<=(?=lookahead).*).
Supports union and intersection of character classes.
Has the most extensive support for Unicode, with character classes for "Unicode scripts, blocks, categories and binary properties".
\Q...\E as in Perl/PCRE.

Ruby
In recent versions, this flavour is similarly powerful as PCRE, including the support for subroutine calls. Like Java, it also supports union and intersection of character classes. One special feature is the built-in character class for hex digits: \h (and the negated \H).
The most useful feature for golfing though is how Ruby handles quantifiers. Most notably, it's possible to nest quantifiers without parentheses. .{5,7}+ works and so does .{3}?. Also, as opposed to most other flavours, if the lower bound on a quantifier is 0 it can be omitted, e.g. .{,5} is equivalent to .{0,5}.
As for subroutines, the major difference between PCRE's subroutines and Ruby's subroutines, is that Ruby's syntax is a byte longer (?n) vs \g<n>, but Ruby's subroutines can be used for capturing, whereas PCRE resets captures after a subroutine finishes.
Finally, Ruby has different semantics for line-related modifiers than most other flavours. The modifier that's usually called m in other flavours is always on in Ruby. So ^ and $ always match the beginning and end of a line not just the beginning and end of the string. This can save you a byte if you need this behaviour, but it will cost you extra bytes if you don't, because you'll have to replace ^ and $ with \A and \z, respectively. In addition to that, the modifier that is usually called s (which makes . match linefeeds) is called m in Ruby instead. This doesn't affect byte counts, but should be kept in mind to avoid confusion.
Python
Python has a solid flavour, but I'm not aware of any particularly useful features that you wouldn't find anywhere else.
However, there is the regex module, which is intended to replace the re module at some point, and which contains a lot of interesting features. In addition to adding support for recursion, variable-length lookbehinds and character class combination operators, it also has the unique feature of fuzzy matching. In essence you can specify a number of errors (insertions, deletions, substitutions) which are allowed, and the engine will also give you approximate matches.
ECMAScript
The ECMAScript flavour is very limited, and hence rarely very useful for golfing. The only thing it's got going for it is the negated empty character class [^] to match any character as well as the unconditionally failing empty character class [] (as opposed to the usual (?!)). Unfortunately, the flavour does not have any features which makes the latter useful for normal problems.
Lua
Lua has its own fairly unique flavour, which is quite limited (e.g. you can't even quantify groups) but does come with a handful of useful and interesting features.

It's got a large number of shorthands for built-in character classes, including punctuation, upper/lower case characters and hex digits.
With %b it supports a very compact syntax to match balanced strings. E.g. %b() matches a ( and then everything up to a matching ) (correctly skipping inner matched pairs). ( and ) can be any two characters here.

Boost
Boost's regex flavour is essentially Perl's. However, it has some nice new features for regex substitution, including case changes and conditionals. The latter is unique to Boost as far as I'm aware.

Note that look-ahead in look-behind will punch through the bound limit in the look-behind. Tested in Java and PCRE.

Isn't .?+ equivalent to .*?

@CalculatorFeline The former is a possessive 0-or-1 quantifier (in flavours that support possessive quantifiers), the latter is a 0-or-more quantifier.

@CalculatorFeline ah I understand the confusion. There was a typo.

I'd suggest adding a note about how Go's regexp package is a highly limited subset of PCRE (specifically, only regexes that are accepted by RE2).

Know your character classes
Most regex flavours have predefined character classes. For example, \d matches a decimal digit, which is three bytes shorter than [0-9]. Yes, they might be slightly different as \d may also match Unicode digits as well in some flavours, but for most challenges this won't make a difference.
Here are some character classes found in most regex flavours:
\d      Match a decimal digit character
\s      Match a whitespace character
\w      Match a word character (typically [a-zA-Z0-9_])

In addition, we also have:
\D \S \W

which are negated versions of the above.
Be sure to check your flavour for any additional escape codes it might have. For example, PCRE has \R for newlines and Lua even has classes such as lowercase and uppercase characters.
(Thanks to @HamZa and @MartinBüttner for pointing these out)

\R for newlines in PCRE.

Don't bother with non-capturing groups (unless...)
This tip applies to (at least) all popular Perl-inspired flavours.
This may be obvious, but (when not golfing) it's good practice to use non-capturing groups (?:...) whenever possible. These two extra characters ?: are wasteful when golfing though, so just use capturing groups, even if you're not going to backreference them.
There's one (rare) exception though: if you happen to backreference group 10 at least 3 times, you can actually save bytes by turning an earlier group into a non-capturing group, such that all those \10s become \9s. (Similar tricks apply, if you use group 11 at least 5 times and so on.)

Why does 11 need 5 times to be worth it when 10 requires 3?

@QPaysTaxes being able to use $9 instead of $10 or $11 once saves one byte. Turning $10 into $9 requires one ?:, which is two bytes, so you'll need three $10s to save something. Turning $11 into $9 requires two ?:s which is four bytes, so you'll need five $11s to save something (or five of $10 and $11 combined).

Recursion for pattern reuse
A handful of flavours support recursion (to my knowledge, Perl, PCRE and Ruby). Even when you're not trying to solve recursive problems, this feature can save a lot of bytes in more complicated patterns. There is no need to make the call to another (named or numbered) group inside that group itself. If you have a certain pattern that appears several times in your regex, just group it and refer to it outside that group. This is no different from a subroutine call in normal programming languages. So instead of
...someComplexPatternHere...someComplexPatternHere...someComplexPatternHere...

in Perl/PCRE you could do:
...(someComplexPatternHere)...(?1)...(?1)...

or in Ruby:
...(someComplexPatternHere)...\g<1>...\g<1>...

provided that is the first group (of course, you can use any number in the recursive call).
Note that this is not the same as a backreference (\1). Backreferences match the exact same string that the group matched last time. These subroutine calls actually evaluate the pattern again. As an example for someComplexPatternHere take a lengthy character class:
a[0_B!$]b[0_B!$]c[0_B!$]d

This would match something like
aBb0c!d

Note that you cannot use backreferences here while preserving the behaviour. A backreference would fail on the above string, because B and 0 and ! are not the same. However, with subroutine calls, the pattern is actually reevaluated. The above pattern is completely equivalent to
a([0_B!$])b(?1)c(?1)d

Capturing in subroutine calls
One note of caution for Perl and PCRE: if group 1 in the above examples contains further groups, then the subroutine calls will not remember their captures. Consider this example:
(\w(\d):)\2 (?1)\2 (?1)\2

This will not match
x1:1 y2:2 z3:3

because after the subroutine calls return, the new capture of group 2 is discarded. Instead, this pattern would match this string:
x1:1 y2:1 z3:1

This is different from Ruby, where subroutine calls do retain their captures, so the equivalent Ruby regex (\w(\d):)\2 \g<1>\2 \g<1>\2 would match the first of the examples above.

You can use \1 for Javascript. And PHP too (I guess).

@IsmaelMiguel This is not a backreference. This actually evaluates the pattern again. For instance (..)\1 would match abab but fail on abba whereas (..)(?1) will match the latter. It's actually a subroutine call in the sense that the expression is applied again, instead of literally matching what it matched last time.

Wow, I had no idea! Learning something new everyday

In .NET (or other flavors without this feature): (?=a.b.c)(.[0_B!$]){3}d

@user23013 that seems very specific to this particular example. I'm not sure that's applicable if I reuse a certain subpattern in various lookarounds.

Causing a match to fail
When using regex to solve computational problems or match highly non-regular languages, it is sometimes necessary to make a branch of the pattern fail regardless of where you are in the string. The naive approach is to use an empty negative lookahead:
(?!)

The contents (the empty pattern) always matches, so the negative lookahead always fails. But more often than not, there is a much simpler option: just use a character you know will never appear in the input. E.g. if you know your input will always consist only of digits, you can simply use
!

or any other non-digit, non-meta character to cause failure.
Even if your input could potentially contain any substrings whatsoever, there are shorter ways than (?!). Any flavour which allows anchors to appear within a pattern as opposed to the end, could use either of the following 2-character solutions:
a^
$a

Note however that some flavours will treat ^ and $ as literal characters in these positions, because they obviously don't actually make sense as anchors.
In the ECMAScript flavour there is also the rather elegant 2-character solution
[]

This is an empty character class, which tries to make sure that the next characters is one of those in the class - but there are no characters in the class, so this always fails. Note that this won't work in any other flavour, because character classes can't usually be empty.

Optimize you OR's
Whenever you have 3 or more alternatives in your RegEx:
/aliceblue|antiquewhite|aquamarine|azure/

Check to see if there's a common start:
/a(liceblue|ntiquewhite|quamarine|zure)/

And maybe even a common ending?
/a(liceblu|ntiquewhit|quamarin|zur)e/

Note: 3 is just the start and would account for the same length, 4+ would make a difference

But what if not all of them have a common prefix? (whitespace only added for clarity)
/aliceblue|antiquewhite|aqua|aquamarine|azure
|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood
|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan/

Group them, as long as the 3+ rule makes sense:
/a(liceblue|ntiquewhite|qua|quamarine|zure)
|b(eige|isque|lack|lanchedalmond|lue|lueviolet|rown|urlywood)
|c(adetblue|hartreuse|hocolate|oral|ornflowerblue|ornsilk|rimson|yan)/

Or even generalise if the entropy satisfies your usecase:
/\w(liceblue|ntiquewhite|qua|quamarine|zure
|eige|isque|lack|lanchedalmond|lue|lueviolet|rown|urlywood
|adetblue|hartreuse|hocolate|oral|ornflowerblue|ornsilk|rimson|yan)/

^ in this case we're sure we don't get any clue or crown slack Ryan
This "according to some tests" also improves performance, as it provides an anchor to start at.

If the common start or end is longer than one character, even grouping two can make a difference. Like aqua|aquamarine → aqua(|marine) or aqua(marine)?.

This one is fairly simple, but worth stating:
If you find yourself repeating the character class [a-zA-Z] you can probably just use [a-z] and append the i (case-insensitive modifier) to your regex.
For example, in Ruby, the following two regexes are equivalent:
/[a-zA-Z]+\d{3}[a-zA-Z]+/
/[a-z]+\d{3}[a-z]/i - 7 bytes shorter
For that matter, the other modifiers can shorten your total length as well. Instead of doing this:
/(.|\n)/
which matches ANY character (because dot doesn't match newline), use the single-line modifier s, which makes dot match newlines.
/./s - 3 bytes shorter

In Ruby, there are a ton of built-in Character Classes for regex. See this page and search for "Character Properties".
A great example is the "Currency Symbol". According to Wikipedia there are a ton of possible currency symbols, and to put them in a character class would be very expensive ([$฿¢₡Ð₫€.....]) whereas you can match any of them in 6 bytes: \p{Sc}

Excepting JavaScript, where s modifier is not supported. :( But there you can use JavaScript's proprietary /[^]/ trick.

Note that (.|\n) doesn't even work in some flavours, because . often also doesn't match other types of line separators. However, the customary way to do this (without s) is [\s\S] which is the same bytes as (.|\n).

@MartinBüttner, my idea was to keep it together with the other line ending related tips. But if you feel this answer is more about modifiers, I have no objections if you repost it.

@manatwork done (and added a related non-ES specific trick as well)

\K instead of positive lookbehind
PCRE and Perl support the escape sequence \K, which resets the beginning of the match. That is ab\Kcd will require your input string to contain abcd but the reported match will only be cd.
If you are using a positive lookbehind at the start of your pattern (which is probably the most likely place), then in most cases, you can use \K instead and save 3 bytes:
(?<=abc)def
abc\Kdef

This is equivalent for most purposes, but not entirely. The differences bring both advantages and disadvantages with them:

Upside: PCRE and Perl don't support arbitrary-length lookbehinds (only .NET does). That is, you can't do something like (?<=ab*). But with \K you can put any sort of pattern in front of it! So ab*\K works. This actually makes this technique vastly more powerful in the cases where it's applicable.
Upside: Lookarounds don't backtrack. This is relevant if you want to capture something in the lookbehind to backreference later, but there are several possible captures which all lead to valid matches. In this case, the regex engine would only ever try one of those possibilities. When using \K that part of the regex is being backtracked like everything else.
Downside: As you probably know, several matches of a regex cannot overlap. Often, lookarounds are used to partially work around this limitation, since the lookahead can validate a portion of the string that was already consumed by an earlier match. So if you wanted to match all the characters that followed ab you might use (?<=ab).. Given the input
ababc

this would match the second a and the c. This cannot be reproduced with \K. If you used ab\K., you would only get the first match, because now the ab is not in a lookaround.

If a pattern uses the \K escape sequence within a positive  assertion, the reported start of a successful match can be greater than the end of the match.

@hwnd My point is that given ababc, there is no way to match both the second a and the c with \K. You'll only get one match.

You're correct, not with the feature itself. You would have to anchor with \G

@hwnd Ah I see your point now. But I guess at that point (from a golfing perspective) you're better off with a negative lookbehind, becaue you actually might even need it anyway since you can't be sure that the . from the last match was actually an a.

Interesting use of \K =)

A simple language parser
You can build a very simple parser with an RE like \d+|\w+|".*?"|\n|\S. The
tokens you need to match are separated with the RE 'or' character.
Each time the RE engine tries to match at the current position in the text, it
will try the first pattern, then the second, etc. If it fails (on a space
character here for example), it moves on and tries the matches again. Order is
important. If we placed the \S term before the \d+ term, the \S would
match first on any non-space character which would break our parser.
The ".*?" string matcher uses a non-greedy modifier so we only match one
string at a time. If your RE doesn't have non-greedy functions, you can use
"[^"]*" which is equivalent.
Python Example:
text = 'd="dogfinder"\nx=sum(ord(c)*872 for c in "fish"+d[3:])'
pat = r'\d+|\w+|".*?"|\n|\S'
print re.findall(pat, text)

['d', '=', '"dogfinder"', '\n', 'x', '=', 'sum', '(', 'ord', '(', 'c', ')',
    '*', '872', 'for', 'c', 'in', '"fish"', '+', 'd', '[', '3', ':', ']', ')']

Golfed Python Example:
# assume we have language text in A, and a token processing function P
map(P,findall(r'\d+|\w+|".*?"|\n|\S',A))

You can adjust the patterns and their order for the language you need to match.
This technique works well for JSON, basic HTML, and numeric expressions. It has been used successfully many times with Python 2, but should be general enough to work in other environments.

Capturing groups hold the last value matched
(REGEX)* will hold in capturing group 1 the last match of REGEX. (REGEX) can be combined with any such repeaters.
For getting the last character of a string, there is the straightforward 5-byter
.*(.)

which captures the last character in capturing group 1. Another byte can be saved by noting the point in the title of this post, giving the 4-byter
(.)*

Another example, getting the penultimate character
.*(.).        # 6 bytes
(.)*.         # 5 bytes

Matching any character
Update: Since the ECMAScript 2018 specification, the flavor has the classic dotAll flag that matches all characters, so the following quoted part is now only true if your browser or system uses a very old version that predates this 2018 update, which would be unusual:

The ECMAScript flavour is lacking the s modifiers which makes .
match any character (including newlines). This means there is no
single-character solution to matching completely arbitrary characters.

The following is the unedited rest of this older answer:
The standard solution in other flavours (when one doesn't want to use s for some reason) is [\s\S]. However, ECMAScript is the only flavour (to my knowledge) which supports empty character classes, and hence has a much shorter alternative: [^]. This is a negated empty character class - that is, it matches any character whatsoever.
Even for other flavours, we can learn from this technique: if we don't want to use s (e.g. because we still need to usual meaning of . in other places), there can still be a shorter way to match both newline and printable characters, provided there is some character we know doesn't appear in the input. Say, we're processing numbers delimited by newlines. Then we can match any character with [^!], since we know that ! won't ever be part of the string. This saves two bytes over the naive [\s\S] or [\d\n].

In Perl, \N means exactly what . means outside of /s mode, except it isn't affected by a mode.

Optional expressions
It is sometimes useful to remember that
(abc)?

is mostly the same as
(abc|)

There is a small difference though: in the first case, the group either captures abc or doesn't capture at all. The latter case would make a backreference fail unconditionally. In the second expression, the group will either capture abc or an empty string, where the latter case would make a backreference match unconditionally. To emulate the latter behaviour with ? you'd need to surround everything in another group which would cost two bytes:
((abc)?)

The version using | is also useful when you want to wrap the expression in some other form of group anyway and don't care about the capturing:
(?=(abc)?)
(?=abc|)

(?>(abc)?)
(?>abc|)

Finally, this trick can also be applied to ungreedy ? where it saves a byte even in its raw form (and consequently 3 bytes when combined with other forms of groups):
(abc)??
(|abc)

Forget a captured group after a subexpression (PCRE)
For this regex:
^((a)(?=\2))(?!\2)

If you want to clear the \2 after group 1, you can use recursion:
^((a)(?=\2)){0}(?1)(?!\2)

It will match aa while the previous one won't. Sometimes you can also use ?? or even ? in place of {0}.
This might be useful if you used recursions a lot, and some of the backreferences or conditional groups appeared in different places in your regex.
Also note that atomic groups are assumed for recursions in PCRE. So this won't match a single letter a:
^(a?){0}(?1)a

I didn't try it in other flavors yet.
For lookaheads, you can also use double negatives for this purpose:
^(?!(?!(a)(?=\1))).(?!\1)

Use atomic groups and possessive quantifiers
I found atomic groups ((?>...)) and possessive quantifiers (?+, *+, ++, {m,n}+) sometimes very useful for golfing. It matches a string and disallows backtracking later. So it will only match the first matchable string which is found by the regex engine.
For example: To match a string with odd number of a's at the beginning, which is not followed by more a's, you can use:
^(aa)*+a
^(?>(aa)*)a

This allows you to use things like .* freely, and if there is an obvious match, there won't be another possibility matching too many or too few characters, which may break your pattern.
In .NET regex (which doesn't have possessive quantifiers), you can use this to pop group 1 the greatest multiple of 3 (with maximum 30) times (not golfed very well):
(?>((?<-1>){3}|){10})

In flavors that have neither of the two features, such as ECMAScript, you could usually use lookahead for this, but may not worth it unless you already need lookahead anyway:
(?=(atomic group))\1

ECMAscript is also missing possessive quantifiers or atomic groups :(

@CSᵠ Actually there is a way, with a few more characters.

Multiple lookaheads that always match (.NET)
If you have 3 or more lookahead constructs that always match (to capture subexpressions), or there is a quantifier on a lookahead followed by something else, so they should be in a not necessarily captured group:
(?=a)(?=b)(?=c)
((?=a)b){...}

These are shorter:
(?(?(?(a)b)c))
(?(a)b){...}

where a should not be the name of a captured group. You can't use | to mean the usual thing in b and c without adding another pair of parentheses.
Unfortunately, balancing groups in the conditionals seemed buggy, making it useless in many cases.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Identifying Sequences for Cellular Automata
Background
For the purposes of this challenge, an n-state cellular automaton is simply a binary function f that takes two numbers from the state set {0, 1, ..., n-1} as inputs, and returns another number from that set as output.
It can be applied to a list of numbers L = [x0, x1, x2, ..., xk-1] of length at least 2 by
f(L) = [f(x0, x1), f(x1, x2), f(x2, x3), ..., f(xk-2, xk-1)]
Note that the resulting list has one fewer element than the original.
A spacetime diagram of f starting from L is the list of lists obtained by repeatedly applying f to L, and collecting the results in a list.
The final list has length 1.
We say that the list L is an identifying sequence for f, if every two-element list over the state set is a contiguous sublist of some row of the spacetime diagram starting from L.
This is equivalent to the condition that no other n-state CA has that exact spacetime diagram.
Input
Your inputs are an n-by-n integer matrix M, a list of integers L of length at least 2, and optionally the number n.
The matrix M defines an n-state CA f by f(a,b) = M[a][b] (using 0-based indexing).
It is guaranteed that n > 0, and that M and L only contain elements of the state set {0, 1, ..., n-1}.
Output
Your output shall be a consistent truthy value if L is an identifying sequence for the CA f, and a consistent falsy value otherwise.
This means that all "yes"-instances result in the same truthy value, and all "no"-instances result in the same falsy value.
Example
Consider the inputs n = 2, M = [[0,1],[1,0]], and L = [1,0,1,1].
The matrix M defines the binary XOR automaton f(a,b) = a+b mod 2, and the spacetime diagram starting from L is
1 0 1 1
1 1 0
0 1
1

This diagram does not contain 0 0 on any row, so L is not an identifying sequence, and the correct output is False.
If we input L = [0,1,0,0] instead, the spacetime diagram is
0 1 0 0
1 1 0
0 1
1

The rows of this diagram contain all pairs drawn from the state set, namely 0 0, 0 1, 1 0 and 1 1, so L is an identifying sequence and the correct output is True.
Rules
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
Trivial automaton
[[0]] [0,0] 1 -> True
Binary XOR
[[0,1],[1,0]] [1,0,1,1] 2 -> False
[[0,1],[1,0]] [1,0,1,0] 2 -> True
[[0,1],[1,0]] [0,1,0,0] 2 -> True
Addition mod 3
[[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,0] 3 -> False
[[0,1,2],[1,2,0],[2,0,1]] [0,1,1,0,0,0,1,0,1] 3 -> True
Multiplication mod 3
[[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,0,0,1,0,1] 3 -> False
[[0,0,0],[0,1,2],[0,2,1]] [0,1,1,2,2,2,1,0,1] 3 -> True
Some 4-state automata
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,0,1,1,1,1] 4 -> False
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,0,0,1,0,1,1,1] 4 -> False
[[3,2,2,1],[0,0,0,1],[2,1,3,1],[0,1,2,3]] [0,1,2,3,3,1,2,3,0] 4 -> True
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,0,1,1,2,2,0,2,1] 4 -> False
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1] 4 -> False
[[0,1,2,1],[1,0,2,0],[2,2,1,0],[1,2,0,0]] [0,3,1,3,2,3,3,0,1,2] 4 -> True

CJam, 53 43 42 bytes
l~:M;_,({_[\1>]zW<_{M\{=}/}%}*;](_*\L*_&,=

This is a very straight-forward implementation of the definition (I took some inspiration from Jakube after my first attempt). It expects input in reverse order on STDIN, using CJam-style arrays:
2 [1 0 1 1] [[0 1][1 0]]

Here is a test harness which runs the code against all inputs (converting them to the correct input format first). The results in the input field aren't actually used. Remove them if you don't trust me. ;)

Python 2: 93 byte
M,L,n=input();a=[]
while L:z=zip(L,L[1:]);a+=z;L=[M[i][j]for i,j in z]
print len(set(a))==n*n

Straightforward implementation: Find all pairs by zipping, memorize them for later and apply M to L. Repeat. Compare the number of unique pairs found.
Input is of the form [[0,1],[1,0]], [0,1,0,0], 2.

Mathematica, 90 83 82 bytes
f=Length[Union@@Last@Reap[#2//.l_List:>Extract[#,Sow/@Partition[l+1,2,1]]]]==#3^2&

Another straight-forward implementation.
Usage:
f[{{0, 1}, {1, 0}}, {0, 1, 0, 0}, 2]

True


text:
Code the shortest for incremental adding up until > 100 in Hack Assembly Language
You can find the Hack Assembly Language specification here: http://www.cs.huji.ac.il/course/2002/nand2tet/docs/ch_4_machine_language.pdf
You can download the Hack Computer emulator here:
http://www.nand2tetris.org/software.php
The goal is to write something similar to this:
int i = 1;
while(i<100){
    i = i+i;
}

My solution is here:
@17     // Set Register A to 17
M = 1   // Set M[17] = 1
@17     // Set Register A to 17  --> This is location 2 btw
D = M   // Set Register D to value stored in M[17]
A = D   // Copy the value found in Register D to A
D = D+A // Set value in D = D + A
@17     // Set Register A to 17
M = D   // Store the value in M[17] to the value of Register D
@100    // Store value 100 in Register A
D = D-A // Set value in D to D - 100
@2      // Set Register A to 2
D;JLT   // If D<0 D is still not greater than 100. Goto location 2

Can you come up with something shorter?

I'm not sure how to understand your question. This site is mainly for programming competitions. Do you want to make a codegolf competition? Or do you only want some tips?

@jakube competition

Then you should edit the question a little bit. 'Something similar to this' is very vague. I would formulate this in another way: E.g. Find the smallest power of two, that is >= 100. In this way the goal is more clearer. Also, I would generalize it to >= n, where n is an input from the user (Not sure how to do this in assembly though). Otherwise someone will hardcode the solution 128.


text:
Water held in a hexagonal rod scuplture
I have bunch of hexagonal rods glued together into an odd sculpture. The rods
are 1 to 99 centimetres (cm) long and 1 square cm in cross-section area. All
rods are glued on a hexagonal face to at least one other rod. The rods are all
aligned at their bottom edge.
After some heavy rain, the sculpture is full of water. How much water does it
hold?
Input
Your program should read in (via stdin or a file) a number of lines consisting of
pairs of spaces and pairs of digits specifying the length of the rods in this format:
  aa  bb
cc  dd  ee
  ff  gg

Each rod (like dd here) is glued to a maximum of 6 surrounding rods as shown in the examples. Missing rods are holes and do not gather water. For example, the input
  04  04
04  01  03
  04  04

would represent the following sculpture:

The centre rod is height 1 (I didn't find a good angle where that rod is also visible). Now the column above that rod could hold 2 cm of water, before it would overflow over the 3 rod on the right. Since none of the other rods can hold any water above them, the answer would be 2. Here are two more complex examples:
Example 2:
55  34  45  66
  33  21  27
23  12  01  77
  36  31  74
answer = 35 (  2 on top of 21
             +11 on top of 12
             +22 on top of 01, before everything overflows over 23)

Example 3:
        35  36  77  22                      23  32  54  24
      33  07  02  04  21                  54  07  07  07  76
    20  04  07  07  01  20              54  11  81  81  07  76
  20  67  67  22  07  01  78          54  07  81  07  81  09  76
20  67  07  67  22  22  07  44  55  54  07  81  07  07  61  07  20
  67  57  50  50  07  07  14  03  02  15  81  99  91  07  81  04
67  07  50      50  87  39  45  41  34  81  07  07  89  07  81  79
  67  07  50  50  07  07  07  27  07  27  81  07  07  79  81  78
20  67  67  07  07  07  07  99  33  46  02  81  07  07  81  01  20
  33  07  07  01  05  01  92          20  02  81  07  81  15  32
    22  07  20  20  07  20              63  02  80  81  15  32
      45  20  01  20  39                  20  15  07  15  32
        23  20  20  29  43  21  18  41  20  66  66  43  21
      90                  99  47  07  20
    50                      20  02  48
  70                          56  20
                                90

answer = 1432

Output
Your program should output a single integer giving the volume of water in cubic
centimetres.
Score
Your score is the byte count of your source code. Lowest wins.
The standard loopholes are prohibited as usual.
This puzzle was inspired by a
SPOJ Question.

I had trouble visualising this the first two times I read it, so I took liberty of adding a diagram and a bit more explanation for the first example. Hope you don't mind.

This is really similar to the other challenges involving shapes filling with water.

@FUZxxl we have other challenges like that ?

@FUZxxl I only recall this challenge, which is very different.

@Optimizer This one is somewhat similar.

@Zgarb Ah, nice find, but I having a hex grid, plus arbitrary shape and holes makes this one a lot trickier (and hence, not a dupe).

@MartinBüttner: Thanks. The diagram and extra explanation are very helpful.

Python 2, 222 bytes
import sys
y=h=v=0;B={}
for l in sys.stdin:
 z=y;y+=2j
 while l:
    if"0"<l:B[z]=int(l[:2])
    l=l[2:];z+=1
while B:C=B;B={b:B[b]for b in B if(h<B[b])+sum(3>abs(c-b)for c in B)/7};a=C==B;h+=a;v+=a*sum(h>B[b]for b in B)
print v

Reads input through STDIN and writes the result to STDOUT.
Explanation
We start at zero and incrementally increase the water level as follows:
Suppose that the water level is h, and we want to add 1 centimeter of water.
We'll call hexagons of height h or less, ones that are about to go (or already are) underwater, "submerged."
The water will spill through any submerged hexagon that isn't surrounded by six neighbors.
We eliminate all such hexagons; of course, now some other submerged hexagons might have less than six neighbors, and they need to be eliminated as well.
We continue in this fashion until convergence, i.e., until all remaining submerged hexagons have exactly six neighbors.
At this point we add the number of submerged hexagons (the gained water volume) to the total count, and increment the water level.
Eventually, all the hexagons will have been eliminated and we halt.

You should be able to shave a character by using -3<c-b<3  instead of 3>abs(c-b).

@DLosc Ah, but they're complex numbers ;)

Fascinating.  Did not catch that.

Ruby 299
f=->i{s={}
l=i.lines
y=0
l.map{|r|x=0
r.scan(/../){s[[x,y]]=[v=$&.to_i,v<1?0:99];x+=1}
y+=1}
loop{break if s.map{|c,r|x,y=c
m = [[-1,-1],[1,-1],[-2,0],[2,0],[1,-1],[1,1]].map{|w,z|s[[x+w,y+z]]}.map{|n|n ?n[0]+n[1]:0}.min
r[1]=[0,m-r[0]].max if r[0]+r[1]>m&&r[1]>0}.none?}
s.map{|c,r|r[1]}.reduce :+}

Brief description of the algorithm:

parses the input, and for each rod saves a two-element array of the form [rod_height, water_height]
rods are placed in a hash and indexed by their x,y coordinates
the water leaking part takes into account the rod/water heights of the immediate neighbors

A slightly more readable version is available here: http://ideone.com/cWkamV
Run the golfed version online with tests: http://ideone.com/3SFjPN

scan takes a block argument. You can just do scan(/../){...} instead of 'scan(/../).map{|v|...}. (You don't need the |v|because Inside thescanblock you can$&, $1`, etc.)

@Jordan Great observations! Thanks!


text:
Prelude Syntax-Checker
Prelude is an esoteric programming language, which has very few, but unusual, restrictions on what constitutes a valid program. Any block of printable ASCII text ("block" meaning that lines of printable ASCII are separated by newlines - 0x0A) is valid provided that:

Every (vertical) column of text contains at most one of ( and ).
Ignoring their vertical position, the ( and ) are balanced, that is, each ( is paired with exactly one ) to the right of it, and vice versa.

Write a program or function which, given a string containing printable ASCII and newlines, determines if it constitutes a valid Prelude program. You may take input via STDIN (or closest alternative), command-line argument or function argument. The result may be returned or printed to STDOUT, using any two fixed truthy/falsy values of your choice.
You must not assume that the input is rectangular.
This is code golf, so the shortest submission (in bytes) wins.
Examples
The following are valid Prelude programs (in fact, they're even real Prelude programs):
?1-(v  #1)-
1   0v ^(#    0)(1+0)#)!
    (#)  ^#1-(0 #

1(#  1) v #  - 1+)
    vv (##^v^+
? v-(0 # ^   #)
?
  1+              1-!

And here are a number of inputs, all of which are invalid:
#(#(##)##)##(
)##(##(##)#)#

#(#)
)###

#(##
(##)

(##)
(#)#

(##)
(###

#(#)
(##)

#(#)
###)

#()#
()##

#(#)##
###
###(#)

Does Prelude have comments which could block out a close paren?

@Alex No. The above rules are really all there is to deciding whether a program is valid or not.

Cool, thanks for clarifying. Just wanted to make sure.

Rule 1 - "Every column of text contains at most one of ( and )"; Example 1, line 2: "1   0v ^(#    0)(1+0)#)!" --> I see 3 ) and 2 (. Shouldn't it be only 1 per line?

@IsmaelMiguel you're looking at lines/rows, not columns. There may be only one ( or ) per vertical column.

@MartinBüttner That isn't specified in the question.

@IsmaelMiguel "column" is usually understood to refer to vertical lines (especially in the context of grids). I've clarified it anyway, though.

Are )( and )()( valid programs?

@Blackhole No, those parentheses aren't correctly balanced. "... each ( and be paired with exactly one ) to the right of it, and vice versa."

Okay, thanks for the clarification!

Can we assume the input has a newline at the end?

@Omar yes you can

CJam, 57 56 bytes
qN/z_{_"()"--W<},,\s:Q,{)Q/({_')/,\'(/,-}:T~\sT0e>+z+}/!

Too long, can be golfed a lot. Explanation to be added once I golf it.
Brief explanation
There are two checks in the code:

First filter checks that each column as at most 1 bracket. The final output of the filter is the number of columns with more than 1 brackets.
Second we convert the input into column major format and then split it on each index into two parts.

In each of these two parts, (Number of "(" - Number of ")") should be complimenting each other. So when you add them up, it should result to 0. Any part that fails this property makes the whole input have non matching brackets.
I also have to make sure that "(" are to the left of ")". This means that the value of Number of "(" - Number of ")" cannot be negative for the right side block.

Try it online here

Python 2, 128 119 105 bytes
def F(p):
 v=n=1
 for r in map(None,*p.split("\n")):A,B=map(r.count,"()");n+=B-A;v*=n<2>A+B
 return n*v>0

Did you know that you can map None in Python 2?
Explanation
We want to start by transposing the Prelude so that columns become rows. Usually we would do this with zip, but since zip truncates to the shortest row length and itertools.zip_longest is far too long for code-golf, it seems like there's no short way to do what we want...
Except for mapping None:
>>> print map(None,*[[1,2,3],[4],[5,6]])
[(1, 4, 5), (2, None, 6), (3, None, None)]

Unfortunately (or rather, fortunately for all non-golf purposes), this only works in Python 2.
As for n and v:

n acts like a stack, counting 1 - <number of unmatched '(' remaining>. For every ( we see we subtract 1, and for every ) we see we add 1. Hence if n >= 2 at any point, then we've seen too many )s and the program is invalid. If n doesn't finish on 1, then we have at least one unmatched ( remaining.
v checks validity, and starts at 1. If the program is ever invalid (n >= 2 or A+B >= 2), then v becomes 0 to mark invalidity.

Hence if the program is valid, then by the end we must have n = 1, v = 1. If the program is invalid, then by the end we must either have v = 0, or v = 1, n <= 0. Therefore validity can be succinctly expressed as n*v>0.
(Thanks to @feersum for a multitude of good suggestions which took off 14 bytes!)
Previous, more readable submission:
def F(p):
 p=map(None,*p.split("\n"));v=n=0
 for r in p:R=r.count;A=R("(");B=R(")");n+=A-B;v|=A+B>1or n<0
 return n<1>v

That's an insane use of map...

119 -> 106 def F(p):        v=n=3        for r in map(None,*p.split("\n")):A,B=map(R.count,"()");n+=A-B;v*=n>2>A+B        return n*v==9

@feersum Thanks! I'd been trying to change the or into comparison chaining, but I didn't think of changing |= into *=. Took off another byte though, by making things even more backwards :)

J, 56 bytes
3 :'*/0<: ::0:(+/\*:b),-.|b=.+/+.^:_1]0|:''()''=/];.2 y'

That is an anonymous function accepting a string with a trailing newline and returning 0 or 1. Reading from right to left:

];.2 y, as in the other J submission, cuts the string y at all occurrences of its last character (which is why the input needs a trailing newline) and makes a rectangular matrix whose rows are the pieces, padded with spaces if necessary.
'()'=/ compares every character in that matrix first with ( and then with ) returning a list of two 0-1 matrices.
+.^:_1]0|: turns that list of two matrices into a single matrix of complex numbers. So far the program turns every ( in the input into a 1, every ) into i, and every other character into 0.
b=.+/ assigns the sum of the rows of that complex matrix to b.
-.|b makes a list of 1-|z| for every z in b. The condition that every column contain at most a single parenthesis translates to all these numbers 1-|z| being nonnegative.
+/\*:b is the vector of running sums of the squares of the numbers in b. If every column does contain at most one parenthesis, the squares of the numbers in b are all 0, 1 or -1. The , concatenates this vector with the vector of 1-|z|'s.
now all we need to do is test that the entries of our concatenated vector v are nonnegative reals numbers, this is almost */0<:v, except that that causes an error if some entries of v are not real, so we replace <: with <: ::0: which just returns 0 in case of error.

Great ideas with the complex numbers but you also need to check if 0={:+/\*:b because e.g. ( isn't valid.

Oh, you're right, @randomra, I forgot!

0=(-|)v is 2 bytes shorter for checking non-negative reals. (Let's beat CJam! :P)

Oh, and inv instead of ^:_1  saves another byte.

(-.@|,+/\@:*:)+/+.inv saves 1 more and might help with the balance check (with 0={:)

Back to 56 (with balance checking): 3 :'*/0=({:,]-|)(-.@|,+/\@:*:)+/+.inv]0|:''()''=/];.2 y'.

J, 64 bytes
Input is a string with a trailing newline. Output is 0 or 1.
(0=(1<|s)s+[:(|@{:+(0>])s)[:+/\]s=.+/@:)@(1 _1 0{~[:'()'&i.];.2)

Example usage
   ]in=.'#(#)##',LF,'###',LF,'###(#)',LF
#(#)##
###
###(#)

   ((0=(1<|s)s+[:(|@{:+(0>])s)[:+/\]s=.+/@:)@(1 _1 0{~[:'()'&i.];.2)) in
0

The method is the following

cut input at newlines and put into a matrix   ];.2
map ( / ) / anything else into 1 / -1 / 0 1 _1 0{~[:'()'&i.]
define an s=.+/@: adverb which added to a verb sums the verbs array output
add values in columns   ]s

check positive () balance in every prefix   [:(0>])s)[:+/\]
check equal () balance in the whole list (i.e. in the last prefix)   |@{:@]

add abs(values) in columns and check every element for a max value of 1   (1<|s)s
as all the previous checks yielded positive at failure we add them up and compare to 0 to get the validity of the input   0=]


text:
The Staircase Challenge
Your work is to recreate this piece of art:
                        _____
                       |
                       |
                       |
                       |
                  _____|
                 |
                 |
                 |
                 |
            _____|
           |
           |
           |
           |
      _____|
     |
     |
     |
     |
_____|

The answer must recreate this and print this as a result. All languages allowed, no direct printing of art, ofc, some level of manipulation is required. The answer with the least bytes wins.
Closes on Thursday 6:30 AM UTC or so.
The original thing was shown to me by my friend who did this with Java, he refused to show me the source code and now I'll dazzle him with the brilliance of other languages possibly. :D
You cannot use any alternative character (makes it easier?).

Current leader board

Pyth - 28 bytes - isaacg
CJam - 30 bytes - Runer112
CJam - 32 bytes - Martin Büttner

Highest votes: C - 73 bytes - Paul R

isaacg takes the crown for passing the Staircase Challenge with Pyth. Watch out for more challenges like these on PPCG!

Welcome to Programming Puzzles & Code Golf Stack Exchange! All challenges here require an objective winning criterion, to indisputably decide which solution should win. This looks like a [tag:code-golf] question, i.e. shortest code wins, but I'll let you edit it in yourself in case you want to make it something different. Thanks!

I did mention that the one with the least bytes wins.

Ah, sorry, I missed that. I've edited the proper tag into your question, then.

@Doorknob This is interesting. We ec-ed twice apparently, explains the loss the information which I had to readd.

Do we have to print that 1 weird trailing space on the 6th line ?

More generally, is trailing space allowed? Can I pad this to a rectangle of the width of the first line?

Can we have a trailing newline?

@Optimizer Nope, not necessary. Anything that looks necessarily similar is permitted in accordance to what I stated above.

@MartinBüttner Well, since a trailing newline would reduce the bytes, everyone can do it. No probs. I'm looking for the most optimized code.

Pyth, 29 28
V21++**6/-20N5d*5?d%N5\_<\|N

Try it here.
A pretty straightforward solution, with the "append five spaces or five underscores" trick from @xnor's solution, but with the loop from 0 to 20, not 20 to 0.

I dub you thee, Sir isaacg for passing the Staircase Challenge.

...and now you can enter the staircase

C, 86 80 76 75 73 bytes
c;main(i){for(i=21;i--;c='|')printf("%*s%c\n",i/5*6+5,i%5?"":"_____",c);}

There always has to be that guy who will post a C solution. Upvote for you.

You could get it even shorter by changing the loop to for(i=25;i--;)

@FelixBytow It should be i=26. Besides this, the ' ' could be changed to 32 for an extra character. My solution is 2 characters longer after these optimizations :(

You seem to have an extra step. there are 21 rows in the required output, not 26. Some more optimizations: main(i){for(i=21;i--;)printf("%*s%c\n",i/5*6+5,i%5?"":"_____",i<20?'|':0);} 1. Simplify the formula for length 2. As @Allbeert says, you can use the ascii code for ' ' but why stop at ASCII 32 when ASCII 0 will do. Also it runs fine for me with "" instead of " "

Thanks for all the suggestions guys, and for noticing that I had one stair too many!

For i<20?'|':0 substitute i<20||'|' for one character.

@FUZxxl: nice idea but it doesn't seem to work - I haven't quite worked out whether it's a problem with operator precedence or something else.

Sorry. It should have been i<20&&'|'. Does that work?

Still not quite there unfortunately - since && is a logical operator I guess the result of the expression is either 1 or 0, not '|' or 0 as we would like it to be ? You can play with it here if you like...

How about this to save two bytes in '|' printing? c;main(i){for(i=21;i--;c='|')printf("%*s%c\n",i/5*6+5,i%5?"":"_____",c);}

@Runer112: very devious - I like it - thanks !

Java, 198 158 156 146 bytes
This can probably be shortened a lot. As usual, suggestions are welcome.
void a(){String a="",b="_____",c=b;for(int i=-1;i<20;b=i%5<1?b.replace(c,"     "):i%5>3?b+" "+c:b)a=b+(++i>19?"":"|")+"\n"+a;System.out.print(a);}

Indented (kinda):
void a(){
    String a="",b="_____",c=b;
    for(int i=-1;i<20;b=i%5<1?b.replace(c,"     "):i%5>3?b+" "+c:b)
        a=b+(++i>19?"":"|")+"\n"+a;
    System.out.print(a);
}

Thanks Martin Büttner, Rainbolt, and Geobits.

Honestly, since you did it with Java, I'm impressed.

Brainfuck (1065 Bytes)
It's not pretty, it's not short...but i'll optimize later on!
++++[->++++++++<]>........................
[->+++<]>-.....>++++++++++.[->+++<]>++....
...................-[->++++<]>.>++++++++++
.[->+++<]>++.......................-[->+++
+<]>.>++++++++++.[->+++<]>++..............
.........-[->++++<]>.>++++++++++.[->+++<]>
++.......................-[->++++<]>.>++++
++++++.[->+++<]>++..................[->+++
<]>-.....[->++++<]>.>++++++++++.[->+++<]>+
+.................-[->++++<]>.>++++++++++.
[->+++<]>++.................-[->++++<]>.>+
+++++++++.[->+++<]>++.................-[->
++++<]>.>++++++++++.[->+++<]>++...........
......-[->++++<]>.>++++++++++.[->+++<]>++.
...........[->+++<]>-.....[->++++<]>.>++++
++++++.[->+++<]>++...........-[->++++<]>.>
++++++++++.[->+++<]>++...........-[->++++<
]>.>++++++++++.[->+++<]>++...........-[->+
+++<]>.>++++++++++.[->+++<]>++...........-
[->++++<]>.>++++++++++.[->+++<]>++......[-
>+++<]>-.....[->++++<]>.>++++++++++.[->+++
<]>++.....-[->++++<]>.>++++++++++.[->+++<]
>++.....-[->++++<]>.>++++++++++.[->+++<]>+
+.....-[->++++<]>.>++++++++++.[->+++<]>++.
....-[->++++<]>.>++++++++++.[--->++<]>+++.
....[->++++<]>.

brainfuck is never pretty :) upvote just for making it work

I disagree: http://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output/34699#34699

http://ideone.com/ICtrhv Time limit exceeded I mean, what....

Bizzare...try it here: http://esoteric.sange.fi/brainfuck/impl/interp/i.html

CJam, 36 30 bytes
Try it online.
L{{S5*\+}/S'|5*+]'_5*+}5*1>zN*

My initial 36-byte solution generated the result in the output orientation. Despite my attempts to squeeze more bytes out of the algorithm, I couldn't. Then I saw Martin's brilliant strategy of generating columns instead of rows and transposing the result. I realized that was probably a better approach, so I set off to create a transposition-based solution.
However, my approach to implementing that strategy varies quite a bit. Instead of generating full columns, I use an iterative solution that indents any already-generated "steps" and adds adds a new step at each iteration. So the first iteration of the main loop generates this:
 |||||
_
_
_
_
_

The second iteration of the main loop indents the existing step and adds a new one after it:
      |||||
     _
     _
     _
     _
     _
 |||||
_
_
_
_
_

And the full five iterations of the main loop generate this:
                     |||||
                    _
                    _
                    _
                    _
                    _
                |||||
               _
               _
               _
               _
               _
           |||||
          _
          _
          _
          _
          _
      |||||
     _
     _
     _
     _
     _
 |||||
_
_
_
_
_

After this, all that needs to be done is eliminate the first line, which would otherwise become the unwanted riser for the bottom step, and transpose.

Python 2, 80 77 74 bytes
n=24;exec"print' '*n+'_'*5+'|'*(n<24)+('\\n'+~-n*' '+'|')*4*(n>0);n-=6;"*5

Got rid of the double exec and fit everything into the one print!

CJam, 36 32 bytes
{5*S*'_+a5*~_W<S+5'|*+}5/;]W%zN*

Test it here.
I also tried using an explicit formula, but it's longer in CJam... maybe it helps someone else:
21,29,ff{_2$5/)6*(=@@6/5*=_++" |_|"=}W%N*

Explanation
I found that the staircase can be built much more easily if you a) transpose the grid and b) reverse the lines:
_
_
_
_
_
 |||||
     _
     _
     _
     _
     _
      |||||
          _
          _
          _
          _
          _
           |||||
               _
               _
               _
               _
               _
                |||||
                    _
                    _
                    _
                    _
                    _

So first I'm building that, then reverse, then transpose.
{                     }5/        "For i in [0 .. 4].";
 5*S*'_+                         "Get a string of 5*i spaces and append _.";
        a5*~                     "Get five such lines.";
            _W<S+                "Duplicate the last, remove the _, add a space.";
                 5'|*+           "Add 5 copies of |.";
                         ;       "The above creates a row too many, so discard the last one.";
                          ]W%zN* "Wrap everything in an array, reverse, transpose, riffle
                                  with newlines.";

Okay, someone's did it with 30 bytes.

Clip, 46
{:24S:5'_m[z{*4,:+5*6zS"|
":*6zS:5'_"|
"`}vR4`

Explanation
{               .- Put everything in a list -.
 :24S           .- 24 spaces                -.
 :5'_           .- 5 underscores            -.
 m[z            .- Map...                   -.
    {           .- A list                   -.
     *4         .- 4 of the following       -.
       ,        .- Append                   -.
        :+5*6zS .- 5 + 6 * the iteration of spaces  -.
        "|      .- A pipe and newline       -.
"
     :*6zS      .- 6 * the iteration of spaces      -.
     :5'_       .- 5 underscores            -.
     "|         .- A pipe and newline       -.
"
    `           .- End list (per iteration  -.
   }vR4         .- The mapping is onto {3,2,1,0}    -.

Clip doesn't even have a Wikipedia page. I mean, what....

@therewillbecoffee Many languages on this site don't have a Wikipedia page. That's the fun ;)

@Ypnypn Did you design it? It looks really interesting! Although I'd be interested in a true quine. ;) (That one on the examples page is a bit cheaty.)

ECMAScript 6, 142 138 129 91 bytes
Special thanks to @edc65 for really reworking this.
a=o='',[for(x of!0+o)(o=(a+'     |\n').repeat(4)+a+'_____|\n'+o,a+='      ')],a+'_____\n'+o

out.value=(a=o='',[for(x of!0+o)(o=(a+'     |\n').repeat(4)+a+'_____|\n'+o,a+='      ')],a+'_____\n'+o)
textarea{
  width:300px;
  height:400px;
}
<textarea id="out";></textarea>

The logic of the original version check @edc65 comment for how it morphed.
((f,l,p)=>                  //variables
f(24)+l+p[1]+               //add the non pattern line
[0,1,2,3].map(b=>f(18-6*b)) //add the right number of spaces in front of the 4 steps
.map((a,b)=>f(4,a+f(5)+p)   //the four repeating lines of the step
+a+l)                       //the landing line
.join(p)+p)                 //put it all together
((n,s=' ')=>s.repeat(n)     //create an variable array of some character
,'_____','|\n')             //string literals

You can safely remove the new constructor before Array to save a few bytes.

@hsl thanks for some reason I thought the new was necessary.

Array(n).join(s) is so ES5! did you try repeat

[1,2,3,4].map((a,b) and using just b => [0,1,2,3].map(b (-4)

I run Firefox and it works, pretty nicely!

@edc65 I'll have to remember the repeat function I hadn't seen it yet.

Just for fun, some golfing advice - http://jsfiddle.net/90zp3729/1/ - score 95

@edc65 I added one really dirty hack to your for of loop. !0+o convert a number to a boolean then to a string.

Python 2, 59
n=21
exec"n-=1;print n/5*6*' '+' _'[n%5<1]*5+'|'*(n<20);"*n

The 21 lines are indexed by n in [20,19,...,1,0]. First prints 6 spaces for each "step" we're up (minus 1), computed as n/5*6. Then, prints five spaces, except these are instead underscores for multiples of five. Finally, prints a vertical line, except for the top line n=20.

Nice and straightforward. I like it!

JavaScript, 115 107 96 94 89 87 83 bytes
This is too long to win, but it's the first time I've come up with an answer on PCG.SE, and I'm kind of proud to have made something postable.
With some helpful syntactical advice I shortened the code significantly - even below the scrollbar threshold!
for(s='',y=22;--y;s+='\n')for(x=0;++x<29;)s+=6*~(~-y/5)-~x?4+5*~(x/6)+y?' ':'_':'|'

Nice answer, several things you could do to shorten it are take out the alert. If you run it in the console it works just fine without it. Also, the semicolon inside the last curly brace isn't necessary. You can save 1 byte by using (y/5-.2) instead of ((y-1)/5)

@qw3n thanks for those suggestions; I wasn't sure if the alert was required by the rules.

You could also move the s+='\n' after the y-- and get rid of the curly braces so it looks like for(s='',y=21;y>0;y--,s+='\n'). I also initialized the s inside the for loop so your code is all one statement

Sorry, one last thing you can do is move the the counting up and down of x and y into the conditional part of the loop it would look like this for(s='',y=22;--y;s+='\n')for(x=0;++x<29;)s+=x==6*~~(y/5-.2)+5?'|':y==5*~~(x/6)+1?'_':' '

@qw3n I was just about to change y>0 to y, but your solution goes even further. Thanks a lot for the help!

I thought that was my last one but this should be it for me for(s='',y=22;--y;s+='\n')for(x=0;++x<29;)s+=6*~~(y/5-.2)+5-x?5*~~(x/6)+1-y?' ':'_':'|' if you flip your ternary expression you can test for number - x which is 0 if both terms are equal saving you 2 more bytes.

Tilde games: ~n == -n-1, -~n == n+1, ~-n == n-1, for(s='',y=22;--y;s+='\n')for(x=0;++x<29;)s+=6*~(~-y/5)-~x?4+5*~(x/6)+y?' ':'_':'|' is 83

You guys are amazing.

MATLAB, 68 bytes
I have the strong feeling MATLAB should be able to do better, but I can't think of a way.
p(1:5,6)='|';p(1,1:5)=95;w=blkdiag(p,p,p,p);w(21,25:29)=95;flipud(w)

Creates the stairs upside-down and flips it. My thaumometer broke because of all the magic constants around.
'|' is intentionally left as-is (instead of ascii codepoint) to initialize p and w as a char array.

'|' = 124 anyway, so that doesn't cost any extra chars.

Ruby, 48
25.times{|i|puts" "*(4-i/6)*5+(i%6==0??_*5:?|)}

Old approach, 68
4.times{|i|(?_*5+"
|"*5).each_line{|l|puts" "*(4-i)*5+l}}
puts"_"*5

Welcome to PPCG! A couple of Ruby golfing tips: 1. there's some unnecessary whitespace in there. 2. Single character strings like '_' can be written as ?_. 3. Newlines can be embedded directly in strings (so you can actually do "<linebreakhere>|"). 4. The parentheses around that aren't necessary. The final puts can be replaced with $><< (which allows you to get rid of the space, even after using ?_). Keep it up! :)

Yeah, I just got rid of some whitespace. Thanks! I didn't know about the single character strings.

You can probably also replace (1..4).map by 4.times and then use 4-i instead of 5-i.

Ooh, good call. Done.

Julia, 83 bytes
for n=24:-6:0 print(" "^n*"_"^5*"|"^(n<24)*"\n"*(" "^(n>0?n-1:0)*"|\n"^(n>0))^4)end

In Julia, string concatenation is performed using the * operator and string repetition is performed using ^.

><>, 108 104 100 bytes
cc+::?v~'_____'o\/' 'o  \
?:o'|'\' 'o1-30.o\v!?:-1<}:{oav!?:<4;!
-20.12^?(+cc:ooo/ \~1-'!|'o1. \~ao6

A simple ><> solution, using the same strategy as my Python answer. The main difference is that ><> doesn't have string multiplication (or even strings), so all of that is done with loops.
Explanation
cc+                  Push 24 (call this "n")

[outer loop]
[loop 1, print n spaces]

:                    Copy n (call this "i")
:?                   If i is not zero...
' 'o1-30.                Print space, decrement i and go to start of loop 1

~'_____'ooooo        Pop i and print five underscores
:cc+(?               If n < 24...
'|'o                     Print a pipe
21.                  Otherwise skip pipe printing

[loop 2: print vertical parts of stairs]

?!;                  If n is zero, halt
4                    Push 4 (call this "j")
?!                   If j is zero...
~ao6-20.                 Pop j, print a newline, minus 6 from n and go to start of outer loop
ao                   Print a newline
}:{                  Copy n (call this "k")

[loop 3: print n-1 spaces]

1-                   Decrement k
:?!                  If k is zero...
    ~1-'!|'o1.           Pop k, decrement j, print a pipe and go to start of loop 2
' 'o                 Otherwise print a space and go to start of loop 3

I feel like I will always upvote a ><> answer.

Bash (+tac from coreutils): 110 bytes
This can be pasted directly into the terminal.
(n=;set {1..4};for i do echo "${n}_____|";n+='     ';for i do echo "$n|";done;n+=\ ;done;echo "${n}_____")|tac

Without |tac, it doesn't quite work. And I ran this on Git Bash, so I should kill myself.

Perl, 50
#!perl -l
print$"x6x(-$_/5),($_%5?$":_)x5,"|"x$|++for-20..0

Try me.

Visual FoxPro 9.0, 261 bytes
n = Number of Steps
total of 175 characters, but had to output to file to display correctly - so minus 43 chars for file operations = 132 chars.
n=10
c=CHR(13)
f="st.t"
ERAS (f)
FOR i=n TO 1 STEP -1
    p=(i-1)*6
    =STRTO(PADL("_____",p+5)+IIF(i<n,"|","")+c+IIF(i>1,REPLI(PADL("|"+c,p+1),4),""),f,.t.)
    ?PADL("_____",p+5)+IIF(i<n,"|","")+c+IIF(i>1,REPLI(PADL("|"+c,p+1),4),"")
ENDFOR
MODI COMM (f)

Note to answerer: Byte count is for the absolute working source code, and the byte counter says that it's 261 bytes, so it is.

T-SQL, 276 bytes
declare @x int declare @y int declare @w varchar(30) declare @l char(5) set @l='_____' set @x=23 while @x > 4 begin set @w=replicate(' ',@x) set @y=0 if @x=23 print @w+' '+@l else print @w+' '+@l+'|' while @y < 4 begin set @y=1+@y print @w+'|' end set @x=@x-6 end print @l+'|'