Merge pull request from eyougo/master

fix a bug of RegexSelector when regex has zero-width assertions.
pull/493/head
Yihua Huang committed by GitHub
commit 676758349f

@ -28,8 +28,7 @@ public class RegexSelector implements Selector {
} }
// Check bracket for regex group. Add default group 1 if there is no group. // Check bracket for regex group. Add default group 1 if there is no group.
// Only check if there exists the valid left parenthesis, leave regexp validation for Pattern. // Only check if there exists the valid left parenthesis, leave regexp validation for Pattern.
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") == if ( ! hasGroup(regexStr) ){
StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:")) {
regexStr = "(" + regexStr + ")"; regexStr = "(" + regexStr + ")";
} }
this.regexStr = regexStr; this.regexStr = regexStr;
@ -45,6 +44,30 @@ public class RegexSelector implements Selector {
this(regexStr, 1); this(regexStr, 1);
} }
private boolean hasGroup(String regexStr) {
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:")){
return false;
}
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?=") - StringUtils.countMatches(regexStr, "\\(?=") ) {
return false;
}
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?<") - StringUtils.countMatches(regexStr, "\\(?<") ) {
return false;
}
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?!") - StringUtils.countMatches(regexStr, "\\(?!") ) {
return false;
}
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?#") - StringUtils.countMatches(regexStr, "\\(?#") ) {
return false;
}
return true;
}
@Override @Override
public String select(String text) { public String select(String text) {
return selectGroup(text).get(group); return selectGroup(text).get(group);

@ -22,4 +22,20 @@ public class RegexSelectorTest {
String select = regexSelector.select(source); String select = regexSelector.select(source);
Assertions.assertThat(select).isEqualTo(source); Assertions.assertThat(select).isEqualTo(source);
} }
@Test
public void testRegexWithZeroWidthAssertions() {
String regex = "^.*(?=\\?)";
String source = "hello world?xxxx";
RegexSelector regexSelector = new RegexSelector(regex);
String select = regexSelector.select(source);
Assertions.assertThat(select).isEqualTo("hello world");
regex = "\\d{3}(?!\\d)";
source = "123456asdf";
regexSelector = new RegexSelector(regex);
select = regexSelector.select(source);
Assertions.assertThat(select).isEqualTo("456");
}
} }

Loading…
Cancel
Save