你能帮助我从最外面的大括号中获取值,搜索字符串会有所不同吗?
String search = "hostProductLineCode:eq(YB) || hostProductLineCode:eq(PB) || (readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00))";
想要从上面获得以下值 YB PB readyDate:GE(2014-01-13T05:00:00);开始日期:GE(2014-01-13T05:00:00)
search = "(readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00)) || (liveDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00))";
想要从上面获得以下值 readyDate:GE(2014-01-13T05:00:00);开始日期:GE(2014-01-13T05:00:00) liveDate:GE(2014-01-13T05:00:00);开始日期:GE(2014-01-13T05:00:00)
search = "hostProductLineCode:eq(YB);hostProductLineCode:eq(PB);(readyDate:ge(2014-01-13T05:00:00)||StartDate:ge(2014-01-13T05:00:00))";
想要从上面获得以下值
YB
PB
readyDate:GE(2014-01-13T05:00:00)||开始日期:GE(2014-01-13T05:00:00)
search = "hostProductLineCode:eq(YB);hostProductLineCode:eq:eq(V);(readyDate:ge(2014-01-13T05:00:00)||StartDate:ge(2014-01-13T05:00:00));(status:eq(V)||status:eq(P))";
希望从上面获得以下值
YB
V
readyDate:ge(2014-01-13T05:00:00)||StartDate:ge(2014-01-13T05:00:00));(status:eq(V)||status:eq(P)
我在下面试过
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(search);
while (m.find()) {
System.out.println(m.group());
}
答案 0 :(得分:0)
根据||
拆分字符串,然后使用\(.*\)
正则表达式进行匹配。 .*
是贪婪的量词。它试图获得尽可能大的匹配。
答案 1 :(得分:0)
这里有一些代码 注意:它是C#,但如果需要,您可以轻松转换为Java或JS。它的注释使您可以轻松地遵循逻辑。
它基本上扫描你的字符串并将所有东西复制到外部括号中:
void Main()
{
String search = @"hostProductLineCode:eq(YB) ||
hostProductLineCode:eq(PB) ||
(readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00))";
GetParenthesis(search).Dump();
search = @"(readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00))
|| (liveDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00))";
GetParenthesis(search).Dump();
}
// Define other methods and classes here
private IEnumerable<string> GetParenthesis(string aSource) {
int status = 0; // you'll copy chars when this is 1 or bigger
List<string> list_of_string = new List<string>(); // Hold the strings
StringBuilder temp_string = new StringBuilder(); // Hold temp string we're copying
for (int i = 0; i < aSource.Length; i++)
{
// Deal with open bracket
if (aSource[i].Equals('(')) {
if (status ==0)
i++; // to skip the first "("
status++;
}
// Deal with close bracket
else if (aSource[i].Equals(')')) {
status--;
if (status==0) { // need to add to list
list_of_string.Add(temp_string.ToString());
temp_string.Clear(); // reset temp string
}
}
// Copy if in between brackets
if (status>=1)
temp_string.Append(aSource[i]);
}
return list_of_string;
}
运行主要部分(我使用linqpad),将返回:
List<String> (3 items)
YB
PB
readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00)
List<String> (2 items)
readyDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00)
liveDate:ge(2014-01-13T05:00:00);StartDate:ge(2014-01-13T05:00:00)
这看起来像你想要的。