Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/main/java/net/datafaker/Faker.java
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,20 @@ public String regexify(String regex) {
return fakeValuesService.regexify(regex);
}

/**
* Generates a String by example. The output string will have the same pattern as the input string.
*
* For example:
* "AAA" becomes "KRA"
* "abc" becomes "uio"
* "948" becomes "345"
* "A19c" becomes "Z20d"
*
* @param example The input string
* @return The output string based on the input pattern
*/
public String examplify(String example) {return fakeValuesService.examplify(example);}

public RandomService random() {
return this.randomService;
}
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/net/datafaker/service/FakeValuesService.java
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,31 @@ public String regexify(String regex) {
return generex.random();
}

/**
* Generates a String by example. The output string will have the same pattern as the input string.
*/
public String examplify(String example) {
StringBuilder sb = new StringBuilder();
if(example == null) {
return null;
}

char[] chars = example.toCharArray();

for (char character : chars) {
if (Character.isLetter(character)) {
sb.append(letterify("?", Character.isUpperCase(character)));
} else if(Character.isDigit(character)) {
sb.append(randomService.nextInt(10));
} else {
sb.append(character);
}
}

return sb.toString();

}

/**
* Returns a string with the '?' characters in the parameter replaced with random alphabetic
* characters.
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/net/datafaker/FakerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,31 @@

public class FakerTest extends AbstractFakerTest {

@Test
public void examplifyUppercaseLetters() {
assertThat(faker.examplify("ABC"), matchesRegularExpression("[A-Z]{3}"));
}

@Test
public void examplifyLowercaseLetters() {
assertThat(faker.examplify("abc"), matchesRegularExpression("[a-z]{3}"));
}

@Test
public void examplifyNumbers() {
assertThat(faker.examplify("489321"), matchesRegularExpression("[0-9]{6}"));
}

@Test
public void examplifyMixed() {
assertThat(faker.examplify("abc123ABC1zzz"), matchesRegularExpression("[a-z]{3}[0-9]{3}[A-Z]{3}[0-9][a-z]{3}"));
}

@Test
public void examplifyWithSpacesAndSpecialCharacters() {
assertThat(faker.examplify("The number 4!"), matchesRegularExpression("[A-Z][a-z]{2} [a-z]{6} [0-9]!"));
}

@Test
public void bothifyShouldGenerateLettersAndNumbers() {
assertThat(faker.bothify("????##@gmail.com"), matchesRegularExpression("\\w{4}\\d{2}@gmail.com"));
Expand Down