@@ -578,8 +578,30 @@ public Builder oneOf(final String... pValues) {
578
578
* @return this builder
579
579
*/
580
580
public Builder capture () {
581
+ return this .capture (null );
582
+ }
583
+
584
+ /**
585
+ * Adds named-capture - open brace to current position and closed to suffixes
586
+ * <p>
587
+ * <pre>Example:{@code
588
+ * String text = "[email protected] ";
589
+ * VerbalExpression regex = regex()
590
+ * .find("@")
591
+ * .capture("domain").anything().build();
592
+ * regex.getText(text, "domain"); // => "example.com"
593
+ * }</pre>
594
+ *
595
+ * @return this builder
596
+ * @since 1.6
597
+ */
598
+ public Builder capture (final String name ) {
581
599
this .suffixes .append (")" );
582
- return this .add ("(" );
600
+
601
+ if (name == null || name .trim ().isEmpty ()) {
602
+ return this .add ("(" );
603
+ }
604
+ return this .add ("(?<" + name + ">" );
583
605
}
584
606
585
607
/**
@@ -592,6 +614,16 @@ public Builder capt() {
592
614
return this .capture ();
593
615
}
594
616
617
+ /**
618
+ * Shortcut for {@link #capture(String)}
619
+ *
620
+ * @return this builder
621
+ * @since 1.6
622
+ */
623
+ public Builder capt (final String name ) {
624
+ return this .capture (name );
625
+ }
626
+
595
627
/**
596
628
* Same as {@link #capture()}, but don't save result
597
629
* May be used to set count of duplicated captures, without creating a new saved capture
@@ -716,6 +748,25 @@ public String getText(final String toTest, final int group) {
716
748
return result .toString ();
717
749
}
718
750
751
+ /**
752
+ * Extract exact named-group from string
753
+ * <p>
754
+ * Example is see to {@link Builder#capture(String)}
755
+ *
756
+ * @param toTest - string to extract from
757
+ * @param group - group to extract
758
+ * @return extracted group
759
+ * @since 1.6
760
+ */
761
+ public String getText (final String toTest , final String group ) {
762
+ Matcher m = pattern .matcher (toTest );
763
+ StringBuilder result = new StringBuilder ();
764
+ while (m .find ()) {
765
+ result .append (m .group (group ));
766
+ }
767
+ return result .toString ();
768
+ }
769
+
719
770
/**
720
771
* Extract exact group from string and add it to list
721
772
*
0 commit comments