curious-odd-man / RgxGen

Regex: generate matching and non matching strings based on regex pattern.
Apache License 2.0
86 stars 14 forks source link

Add ability to define what any character "." means #83

Closed fakemail324 closed 1 year ago

fakemail324 commented 1 year ago

I'd like to use RgxGen to generate file names from patterns provided by users. Some of them are like: ^file.*.txt$ I would be very helpful to be able to limit "any character" to some regex like [a-zA-Z0-9-_] to avoid illegal or not desired characters in the file name. It could be similar to solution used in: https://github.com/Cornutum/regexp-gen/blob/master/README.md#what-matches-dot

curious-odd-man commented 1 year ago

Hello! This is now implemented, though only in a snapshot version.

Please feel free to try it out and provide any feedback

    <repositories>
        <repository>
            <id>snapshots-repository</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependency>
        <groupId>com.github.curious-odd-man</groupId>
        <artifactId>rgxgen</artifactId>
        <version>2.0-SNAPSHOT</version>
    </dependency>

Here is a code example (note that API is slightly changed


public class Main {
    public static void main(String[] args) {
        RgxGenProperties properties = new RgxGenProperties();
        RgxGenOption.DOT_MATCHES_ONLY.setInProperties(properties, RgxGenCharsDefinition.of("abc"));
        RgxGen rgxGen = RgxGen.parse(properties, ".");
        String generatedValue = rgxGen.generate();      // Will produce either "a" or "b" or "c".
    }
}
fakemail324 commented 1 year ago

Thank you for the reply. That would also work. You could also consider extending this feature and instead of providing the list of characters that would match the "." you could define the regex that would replace the ".". The workaround I'm using right now is:

public class Main {
    private static final String DOT_PATTERN = "(?<!\\\\)\\.";
    private static final String DOT_REPLACEMENT_PATTERN = "[0-9a-zA-Z]";
    public static void main(String[] args) {
        RgxGen rgxGen = RgxGen.parse(".".replaceAll(DOT_PATTERN, DOT_REPLACEMENT_PATTERN));
        System.out.println(rgxGen.generate());
    }
}