如何用正则表达式去匹配横杠

悬赏:20 发布时间:2008-08-07 提问人:strongwdl (初级程序员)

今天在写代码,用正则表达式去检查mail地址时,我们公司的mail地址比较怪,用了"-",而"-"恰好是正则里的特殊字符,我用\\-去过滤,不成功,有这方面经验的兄弟能不能给个思路?

采纳的答案

2008-08-07 小疯子 (资深程序员)

Java里面应该就是这样匹配的啊!
public class RegexTest extends TestCase {

	public void test() {
		String regex = "[a-zA-Z\\-]";
		
		assertTrue(Pattern.compile(regex).matcher("a").matches());
		assertTrue(Pattern.compile(regex).matcher("A").matches());
		assertTrue(Pattern.compile(regex).matcher("-").matches());

		assertFalse(Pattern.compile(regex).matcher("1").matches());
		assertFalse(Pattern.compile(regex).matcher(".").matches());
		assertFalse(Pattern.compile(regex).matcher(">").matches());
	}

}

提问者对于答案的评价:
谢了,我需要java的

其他回答

	<script type='text/javascript'>
	var myemail = "a-b@gmail.com";
	var parten =/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	if(parten.test(myemail)){
		alert('email地址合法!');
	}else{
	alert('email地址不合法!');
	}
	</script>


Have fun.
qichunren (资深程序员) 2008-08-07
如果只是为了解决 Email 地址的问题,应该使用这个符合 RFC822 标准的 Email 验证正则表达式,PHP 的版本,也被翻译到 Ruby 和 Python 的。rainux+test@gmail.com 这样的地址是符合 RFC822 标准的,在这个正则表达式里可以通过验证,但绝大多数网站注册时都认为这个 Email 地址是不合法的。

http://iamcal.com/publish/articles/php/parsing_email/
rainux (中级程序员) 2008-08-07