Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Greedy vs Lazy in Regular Expressions

The greedy expression can be seen as a True *and* False predicate, meaning true while the token is valid, while being false if the pattern matching hasn't been exhausted.
The lazy expression is the True *or* False predicate, meaning true while the token is valid, or false if the pattern match hasn't been fully exhausted.

irb(main):037:0> "<EM>first</EM>"[/<.+>/] #greedy 
=> "<EM>first</EM>"
irb(main):038:0> "<EM>first</EM>"[/<.+?>/] #lazy
=> "<EM>"
irb(main):039:0> "<EM>first</EM>"[/<[^<>]+>/] # better solution
=> "<EM>"

source: Regular Expression Quick Start [regular-expressions.info]

Creating a circular reference between two objects in Java

This is in some sense the 'right' way of doing it as far as I can figure. Nothing else I've been able to come up with works even close to as well.

public class LazyModules 
{
  static int i = 0;

  static abstract class A{
    abstract B getB();
    int k = i++;
    public String toString() { return "" + k; }
  }

  static abstract class B{
    abstract A getA();
    int k = i++;
    public String toString() { return "" + k; }
  }

  public static void doStuff(A foo, B bar){
    System.out.println("foo = " + foo);
    System.out.println("foo.b = " + foo.getB());
    System.out.println("bar = " + bar);
    System.out.println("bar.a = " + bar.getA()); 
  }

  public static void main(String[] args){
    new Object(){
      final A foo = new A() { B getB() { return bar; }  };
      final B bar = new B() { A getA() { return foo; }  };

      { doStuff(foo, bar); }
    };
  }
}

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS