Skip to content

maybe() method now accepts a builder as parameter #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 5, 2015
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
26 changes: 24 additions & 2 deletions src/main/java/ru/lanwen/verbalregex/VerbalExpression.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package ru.lanwen.verbalregex;

import static java.lang.String.valueOf;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.String.valueOf;

public class VerbalExpression {

private final Pattern pattern;
Expand Down Expand Up @@ -170,6 +170,28 @@ public Builder find(final String value) {
public Builder maybe(final String pValue) {
return this.then(pValue).add("?");
}

/**
* Add a regex to the expression that might appear once (or not)
* Example:
* The following matches all names that have a prefix or not.
* VerbalExpression.Builder namePrefix = regex().oneOf("Mr.", "Ms.");
* VerbalExpression name = regex()
* .maybe(namePrefix)
* .space()
* .zeroOrMore()
* .word()
* .oneOrMore()
* .build();
* regex.test("Mr. Bond/") //true
* regex.test("James") //true
*
* @param pValue - the string to be looked for
* @return this builder
*/
public Builder maybe(final Builder regex) {
return this.group().add(regex).endGr().add("?");
}

/**
* Add expression that matches anything (includes empty string)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -579,4 +579,20 @@ public void testOneOfWithClosedCapture() {
assertThat(testRegex.getText("xxxabcdefzzz", 1), equalTo("abcdef"));
assertThat(testRegex.getText("xxxdefzzz", 1), equalTo("def"));
}

@Test
public void shouldAddMaybeWithOneOfFromAnotherBuilder() {
VerbalExpression.Builder namePrefix = regex().oneOf("Mr.", "Ms.");
VerbalExpression name = regex()
.maybe(namePrefix)
.space()
.zeroOrMore()
.word()
.oneOrMore()
.build();

assertThat("Is a name with prefix", name, matchesTo("Mr. Bond"));
assertThat("Is a name without prefix", name, matchesTo("James"));

}
}