-1

我在正则表达式方面遇到了一些问题。

我有以下类型的字符串,我需要从中解析/获取数据

'Account'.Search = "[Id] is NULL OR NAME = ""0%"""
'Account'.Sort = "NAME, Address"
'Bank Objectives'.Search = "[Active Flg] = "Y""
'Bank'.Search = "[Id] is NULL"
'Bank'.Sort = "Transit"
'Bank Goals'.Search = "[Active Flg] = 'Y'"
.......

以下表达式似乎有效

\s*(?:(?<search>(?:(=['"])?(?:.*)\1|.*)\.Search[^"']*(?:(=['"])?(?:.*)\1|.*))\s*$?(?<sort>(?:(=['"])?(?:.*)\1|.*)\.Sort[^"']*(?:(=['"])?(?:.*)\1|.*))?\s*$?)

我可以得到像

search: 'Account'.Search = '[Id] is NULL OR NAME = ''0%'''
sort: 'Account'.Sort = "NAME, Address"
search: 'Bank Objectives'.Search = "[Active Flg] = "Y""
search: 'Bank'.Search = "[Id] is NULL"
sort: 'Bank'.Sort = "Transit"
search: 'Bank Goals'.Search = "[Active Flg] = 'Y'"

但是,如果输入字符串没有换行符,那么我开始得到

search: 'Account'.Search = '[Id] is NULL OR NAME = ''0%''''Account'.Sort = "NAME, Address"

我基本上从输入字符串中得到的是

Account
  Search = "[Id] is NULL OR NAME = ""0%"""
  Sort = "NAME, Address"
Bank Objectives 
  Search = "[Id] is NULL OR NAME = ""0%"""
  Sort = ""
.....

(=['"])?(?:.*)\1|.*)假设匹配引号,但它似乎也不起作用。

最终目标是将字符串传递[Id] IS NULL or Name =""0%"""给表达式编辑器,允许用户进行更改,然后只更新整个字符串的搜索部分,所以如果用户想要以 开头的帐户名bob,我需要生成

'Account'.Search = "Name like 'bob%'"
'Account'.Sort = "NAME, Address"
'Bank Objectives'.Search = "[Active Flg] = "Y""
'Bank'.Search = "[Id] is NULL"
'Bank'.Sort = "Transit"
'Bank Goals'.Search = "[Active Flg] = 'Y'"
.......

我已经构建了那块,它正在解析这个可以有多个条目的字符串。字符串也可以只包含

"Name like 'bob%'"

所以我要弄清楚它实际上是

'Account'.Search = "名字像'bob%'"

所以我需要知道输入字符串是否与正则表达式匹配

4

1 回答 1

0

使用正则表达式不太可能获得 100% 的解决方案。如果您的语法非常复杂并且可能接收到不符合要求的输入,您希望生成一个词法解析器。有很多关于如何为 .Net 做到这一点的资源。

以下是一些入门链接:

  • http://stackoverflow.com/questions/1669/learning-to-write-a-compiler
  • http://blogs.microsoft.co.il/blogs/sasha/archive/2010/10/06/writing-a-compiler-in-c-lexical-analysis.aspx
  • http://www.antlr.org/

更新:

如果你必须使用正则表达式,为什么不把它分解成几个小问题呢?首先,按换行符拆分并单独解析每一行。然后,使用一组更简单的正则表达式来分解字符串。

例如,将每一行解析为 [obj].[verb] = [rule] :
/'(?<obj>[^']+)'.(?<verb>[^\w=]+\)\s*=\s*"(?<rule>.+)"/

然后将规则解析为具有以下内容的字段:
/\[[^\]+\]/

于 2013-01-03T22:21:56.383 回答