一个算术表达式可能含有以下元素: 数字,运算符(+-*/),正号负号,小括号。 求其正则表达式。。,从网上找到了.net实现,但是转到java时,就报错:Unknown look-behind group...,现将C#的实现放在下面,请高手给出java的实现,谢谢!
Regex regex = new Regex(@ "
^ (?#匹配开头)
[-+]? (?#开头可以出现正负号)
([0-9]+($|[-+*/]))* (?#可选数-符号-数-符号-……-数-符号或结尾)
(
(
(? <o> \() (?#左括号,保存到o名字下)
[-+]? (?#可选正负号)
([0-9]+[-+*/])* (?#可选数-符-数-符……)
)+ (?#可以重复出现左括号)
[0-9]+ (?#左右括号之间最起码需要一个操作数)
( (?#)
(? <-o> \)) (?#右括号,匹配的同时去掉一个左括号)
([-+*/][0-9]+)* (?#可选符-数-符-数……)
)+ (?#可以重复出现右括号,仅当还有左括号剩余)
($|[-+*/]) (?#要么结尾,要么在下一个左括号出现之前出现一个运算符)
)* (?#重复出现左括号)
(?(o)(?!)) (?#如果还有左括号剩余就不匹配任何东西)
$ (?#匹配结尾)
", RegexOptions.IgnorePatternWhitespace);
string[] tests = new string[] {
"1 ",
"1+23 ",
"1+23*456 ",
"1*(23+456) ",
"(3) ",
"((67+8)*9+10)/11 ",
"12+(13*) ",
"(() ",
"((3) ",
"(3)) ",
"+3 ",
"5*(4+3/(-2)) ",
"(5*(4+3/(-2)) ",
"5*(4+3/(-2))) ",
};
foreach (string s in tests)
Console.WriteLine( "{0}: {1} ", regex.IsMatch(s) ? "Good " : " Bad ", s);
Console.ReadKey();
//结果:
//Good: 1
//Good: 1+23
//Good: 1+23*456
//Good: 1*(23+456)
//Good: (3)
//Good: ((67+8)*9+10)/11
// Bad: 12+(13*)
// Bad: (()
// Bad: ((3)
// Bad: (3))
//Good: +3
//Good: 5*(4+3/(-2))
// Bad: (5*(4+3/(-2))
// Bad: 5*(4+3/(-2)))
Regex regex = new Regex(@ "
^ (?#匹配开头)
[-+]? (?#开头可以出现正负号)
([0-9]+($|[-+*/]))* (?#可选数-符号-数-符号-……-数-符号或结尾)
(
(
(? <o> \() (?#左括号,保存到o名字下)
[-+]? (?#可选正负号)
([0-9]+[-+*/])* (?#可选数-符-数-符……)
)+ (?#可以重复出现左括号)
[0-9]+ (?#左右括号之间最起码需要一个操作数)
( (?#)
(? <-o> \)) (?#右括号,匹配的同时去掉一个左括号)
([-+*/][0-9]+)* (?#可选符-数-符-数……)
)+ (?#可以重复出现右括号,仅当还有左括号剩余)
($|[-+*/]) (?#要么结尾,要么在下一个左括号出现之前出现一个运算符)
)* (?#重复出现左括号)
(?(o)(?!)) (?#如果还有左括号剩余就不匹配任何东西)
$ (?#匹配结尾)
", RegexOptions.IgnorePatternWhitespace);
string[] tests = new string[] {
"1 ",
"1+23 ",
"1+23*456 ",
"1*(23+456) ",
"(3) ",
"((67+8)*9+10)/11 ",
"12+(13*) ",
"(() ",
"((3) ",
"(3)) ",
"+3 ",
"5*(4+3/(-2)) ",
"(5*(4+3/(-2)) ",
"5*(4+3/(-2))) ",
};
foreach (string s in tests)
Console.WriteLine( "{0}: {1} ", regex.IsMatch(s) ? "Good " : " Bad ", s);
Console.ReadKey();
//结果:
//Good: 1
//Good: 1+23
//Good: 1+23*456
//Good: 1*(23+456)
//Good: (3)
//Good: ((67+8)*9+10)/11
// Bad: 12+(13*)
// Bad: (()
// Bad: ((3)
// Bad: (3))
//Good: +3
//Good: 5*(4+3/(-2))
// Bad: (5*(4+3/(-2))
// Bad: 5*(4+3/(-2)))
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货