Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2009 Wilfred Springer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package nl.flotsam.xeger;
An object that will generate text from a regular expression. In a way, it's the opposite of a regular expression matcher: an instance of this class will produce text that is guaranteed to match the regular expression passed in.
public class Xeger {
    private final Automaton automaton;
    private final Random random;

    
Constructs a new instance, accepting the regular expression and the randomizer.

Parameters:
regex The regular expression. (Not null.)
random The object that will randomize the way the String is generated. (Not null.)
Throws:
java.lang.IllegalArgumentException If the regular expression is invalid.
    public Xeger(String regexRandom random) {
        assert regex != null;
        assert random != null;
        this. = new RegExp(regex).toAutomaton();
        this. = random;
    }

    
As Xeger(java.lang.String,java.util.Random), creating a java.util.Random instance implicityly.
    public Xeger(String regex) {
        this(regexnew Random());
    }

    
Generates a random String that is guaranteed to match the regular expression passed to the constructor.
    public String generate() {
        StringBuilder builder = new StringBuilder();
        generate(builder.getInitialState());
        return builder.toString();
    }
    private void generate(StringBuilder builderState state) {
        List<Transitiontransitions = state.getSortedTransitions(true);
        if (transitions.size() == 0) {
            assert state.isAccept();
            return;
        }
        int nroptions = state.isAccept() ? transitions.size() : transitions.size() - 1;
        int option = XegerUtils.getRandomInt(0, nroptions);
        if (state.isAccept() && option == 0) {          // 0 is considered stop
            return;
        }
        // Moving on to next transition
        Transition transition = transitions.get(option - (state.isAccept() ? 1 : 0));
        appendChoice(buildertransition);
        generate(buildertransition.getDest());
    }
    private void appendChoice(StringBuilder builderTransition transition) {
        char c = (char) XegerUtils.getRandomInt(transition.getMin(), transition.getMax(), );
        builder.append(c);
    }
New to GrepCode? Check out our FAQ X