A identifies an escape character in java, so you need to escape it if you want to use it on it s own. ( is tab,
is newline etc.)
To escape it, you need to add 1 instead of 2.
下面是一些java代码,可以帮你完成任务:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Assert;
import org.junit.Test;
public class RegexTest {
@Test
public void testPatternWithWhiteSpace(){
Pattern pattern = Pattern.compile("Powered\s*[bB]y.*MyBB");
Matcher matcher = pattern.matcher("Powered By MyBB");
Assert.assertTrue(matcher.matches());
matcher = pattern.matcher("Powered_By MyBB");
Assert.assertFalse(matcher.matches());
}
}
您不必将空白标记放在字符集([])中。
你是对的,s是任何空格。
Regex buddy needs an input as the regular expression is actually written, a literal string expression in eclipse/source code needs to be escaped.
If you would read the pattern from say a properties file, you would not need to escape it.
as I said, Regex Buddy also recognizes
it as such, and if I use s it is not
recognized in Regex Buddy hence the
test fails
i m assuming you mean eclipse there where it fails?
Just add these lines to the test, maybe that explains it a bit more:
matcher = pattern.matcher("Powered
By MyBB");
Assert.assertTrue(matcher.matches());
matcher = pattern.matcher("Powered
,By MyBB");
Assert.assertFalse(matcher.matches());