从字符串中获取方程式

时间:2016-04-11 14:14:29

标签: java regex pattern-matching string-parsing

我有以下格式的字符串

class Student
  def ==(other)
   self.name == other.name
  end  
end

fi = Student.new(name: 'Mark')
sec = Student.new(name: 'Hany')
if (fi == sec)
  # do something here

我希望得到以下结果。

( var1=:key1:'any_value including   space and 'quotes'' AND/OR var2=:key2:'any_value...' AND/OR var3=:key3:'any_value...' )

任何人都可以建议相同的模式/ RE吗?

尝试失败:

首先,我可以将其拆分为:key1:'any_value including space and 'quotes'' :key2:'any_value...' :key3:'any_value...' ,然后再将AND/OR上的其他字符串拆分,依此类推,但查找可以执行此操作的单个RE / Pattern。

2 个答案:

答案 0 :(得分:1)

您可以将此正则表达式与否定模式一起使用以匹配您的数据:

":[^:]+:'.*?'(?=\\s*(?:AND(?:/OR)?|\\)))"

RegEx Demo

<强>解体:

:                         # match a literal :
[^:]+                     # match 1 or more characters that are not :
:                         # match a literal :
'                         # match a literal '
.*?                       # match 0 or more of any characters (non-greedy)
'                         # match a literal '
(?=\s*(?:AND(?:/OR)?|\))) # lookahead to assert there is AND/OR at the end or closing )

答案 1 :(得分:0)

我认为这适用于您的情况 除非您知道解析引号,否则您无法做其他事情。

原始:(?<==)(?:(?!\s*AND/OR).)+
引用:"(?<==)(?:(?!\\s*AND/OR).)+"

展开:

 (?<= = )                  # A '=' behind
 (?:
      (?! \s* AND/OR )     # Not 'AND/OR' in front
      . 
 )+