我想让我的句子如下所示,但是如何使用String.IndexOf方法找到正确的MINVALUE值,以便在给定条件下使用句子中的值更改开始?
的句 的
创建序列“MY_TEST_SEQUENCE”MINVALUE 8 MAXVALUE 999以高速缓存20加速20 NOORDER NOCYCLE开始增加
的结果 的
创建序列“MY_TEST_SEQUENCE”MINVALUE 8 MAXVALUE 999以8个CACHE 20 NOORDER NOCYCLE 1开始增加
的条件 的
我的代码
var startvalue = 0;
if(MINVALUE > 0)
{
startvalue = MINVALUE;
}
Else if(MINVALUE < 0)
{
startvalue = MAXVALUE;
}
var result = String.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE",startvalue)
答案 0 :(得分:0)
看起来像带有捕获组的正则表达式比尝试将字符串分解成碎片更合适。
var regex = new Regex(@".*\s+MINVALUE\s+(-?\d*)\s+MAXVALUE\s+(-?\d*)\s+.*");
var sentence = @"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH 55 CACHE 20 NOORDER NOCYCLE";
var match = regex.Match(sentence);
if (match.Groups.Count != 3)
{
throw new ApplicationException("input string not in expected format");
}
var minValue = int.Parse(match.Groups[1].Value);
var maxValue = int.Parse(match.Groups[2].Value);
var result = string.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE", minValue < 0 ? maxValue : minValue);
答案 1 :(得分:0)
我认为这对你有用;
string sentence = @"CREATE SEQUENCE 'MY_TEST_SEQUENCE' MINVALUE -8 MAXVALUE 999 INCREMENT BY 1 START WITH 55 CACHE 20 NOORDER NOCYCLE";
string pattern = @".*\s+MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[ ]*(?<MaxValue>[\d]*)";
Regex rgx = new Regex(pattern);
Match match = rgx.Match(sentence);
Group gp1 = match.Groups[1];//-8 or 8 (both valid).
Group gp2 = match.Groups[2];//Value after MAXVALUE.
if (gp1.Value.StartsWith("-") == false)//No minus sign,that must be a positive value.
{
string s2 = string.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE", gp1.Value);
MessageBox.Show(s2);
}
else if (gp1.Value.StartsWith("-") == true)//No need for further checking, a value with - will always be smaller.
{
string s2 = string.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE", gp2.Value);
MessageBox.Show(s2);
}