File tree Expand file tree Collapse file tree 2 files changed +40
-2
lines changed
main/java/ru/lanwen/verbalregex
test/java/ru/lanwen/verbalregex Expand file tree Collapse file tree 2 files changed +40
-2
lines changed Original file line number Diff line number Diff line change 1
1
package ru .lanwen .verbalregex ;
2
2
3
+ import static java .lang .String .valueOf ;
4
+
3
5
import java .util .regex .Matcher ;
4
6
import java .util .regex .Pattern ;
5
7
6
- import static java .lang .String .valueOf ;
7
-
8
8
public class VerbalExpression {
9
9
10
10
private final Pattern pattern ;
@@ -170,6 +170,28 @@ public Builder find(final String value) {
170
170
public Builder maybe (final String pValue ) {
171
171
return this .then (pValue ).add ("?" );
172
172
}
173
+
174
+ /**
175
+ * Add a regex to the expression that might appear once (or not)
176
+ * Example:
177
+ * The following matches all names that have a prefix or not.
178
+ * VerbalExpression.Builder namePrefix = regex().oneOf("Mr.", "Ms.");
179
+ * VerbalExpression name = regex()
180
+ * .maybe(namePrefix)
181
+ * .space()
182
+ * .zeroOrMore()
183
+ * .word()
184
+ * .oneOrMore()
185
+ * .build();
186
+ * regex.test("Mr. Bond/") //true
187
+ * regex.test("James") //true
188
+ *
189
+ * @param pValue - the string to be looked for
190
+ * @return this builder
191
+ */
192
+ public Builder maybe (final Builder regex ) {
193
+ return this .group ().add (regex ).endGr ().add ("?" );
194
+ }
173
195
174
196
/**
175
197
* Add expression that matches anything (includes empty string)
Original file line number Diff line number Diff line change @@ -579,4 +579,20 @@ public void testOneOfWithClosedCapture() {
579
579
assertThat (testRegex .getText ("xxxabcdefzzz" , 1 ), equalTo ("abcdef" ));
580
580
assertThat (testRegex .getText ("xxxdefzzz" , 1 ), equalTo ("def" ));
581
581
}
582
+
583
+ @ Test
584
+ public void shouldAddMaybeWithOneOfFromAnotherBuilder () {
585
+ VerbalExpression .Builder namePrefix = regex ().oneOf ("Mr." , "Ms." );
586
+ VerbalExpression name = regex ()
587
+ .maybe (namePrefix )
588
+ .space ()
589
+ .zeroOrMore ()
590
+ .word ()
591
+ .oneOrMore ()
592
+ .build ();
593
+
594
+ assertThat ("Is a name with prefix" , name , matchesTo ("Mr. Bond" ));
595
+ assertThat ("Is a name without prefix" , name , matchesTo ("James" ));
596
+
597
+ }
582
598
}
You can’t perform that action at this time.
0 commit comments