Skip to content

Update RegexSelector.java #51

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 1 commit into from
Dec 21, 2013
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ public RegexSelector(String regexStr, int group) {
if (StringUtils.isBlank(regexStr)) {
throw new IllegalArgumentException("regex must not be empty");
}
if (!StringUtils.contains(regexStr, "(") && !StringUtils.contains(regexStr, ")")) {
// 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.
if (StringUtils.countMatches(regexStr, "(") - StringUtils.countMatches(regexStr, "\\(") ==
StringUtils.countMatches(regexStr, "(?:") - StringUtils.countMatches(regexStr, "\\(?:")) {
regexStr = "(" + regexStr + ")";
}
if (!StringUtils.contains(regexStr, "(") || !StringUtils.contains(regexStr, ")")) {
throw new IllegalArgumentException("regex must have capture group 1");
}
this.regexStr = regexStr;
try {
regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
package us.codecraft.webmagic.selector;

import junit.framework.Assert;
import org.junit.Assert;
import org.junit.Test;

/**
* @author [email protected] <br>
*/
public class RegexSelectorTest {

@Test
public void testInvalidRegex() {
@Test(expected = IllegalArgumentException.class)
public void testRegexWithSingleLeftBracket() {
String regex = "\\d+(";
try {
new RegexSelector(regex);
Assert.assertNotNull(regex);
} catch (Exception e) {
new RegexSelector(regex);
}

}
@Test
public void testRegexWithLeftBracketQuoted() {
String regex = "\\(.+";
String source = "(hello world";
RegexSelector regexSelector = new RegexSelector(regex);
String select = regexSelector.select(source);
Assert.assertEquals(source,select);
}
}