正则表达式来查找公式
我使用不会直接支持我的表/字段参数语法的C#表达文库:正则表达式来查找公式
以下是不直接支持表/字段参数名:
TableName1.FieldName1
[TableName1].[FieldName1]
[Table Name 1].[Field Name 1]
它接受不带空格的字母数字参数或大括号括在方括号内。我想用C#正则表达式替换点分离器和邻近支架到不同的分隔符,那么结果将是如下:
[TableName1|FieldName1]
[TableName1|FieldName1]
[Table Name 1|Field Name 1]
我还需要单引号内跳过任何字符串文字,如:
'TableName1.FieldName1'
,当然,忽略任何数字文字,如:
12345.6789
编辑:感谢您对改善我的问题反馈。希望现在更清楚。
我写了一个全新的答案,现在的问题是澄清:
您可以在一个单一的正则表达式做到这一点。我想,这是相当防弹的,但正如你所看到的,这不完全是自明性的,这就是为什么我*地评论它的原因。希望它是有道理的。
你很幸运,.NET允许重新使用命名捕获组,否则你将不得不在几个步骤中这样做。
resultString = Regex.Replace(subjectString,
@"(?: # Either match...
(?<before> # (and capture into backref <before>)
(?=\w*\p{L}) # (as long as it contains at least one letter):
\w+ # one or more alphanumeric characters,
) # (End of capturing group <before>).
\. # then a literal dot,
(?<after> # (now capture again, into backref <after>)
(?=\w*\p{L}) # (as long as it contains at least one letter):
\w+ # one or more alphanumeric characters.
) # (End of capturing group <after>) and end of match.
| # Or:
\[ # Match a literal [
(?<before> # (now capture into backref <before>)
[^\]]+ # one or more characters except ]
) # (End of capturing group <before>).
\]\.\[ # Match literal ].[
(?<after> # (capture into backref <after>)
[^\]]+ # one or more characters except ]
) # (End of capturing group <after>).
\] # Match a literal ]
) # End of alternation. The match is now finished, but
(?= # only if the rest of the line matches either...
[^']*$ # only non-quote characters
| # or
[^']*'[^']*' # contains an even number of quote characters
[^']* # plus any number of non-quote characters
$ # until the end of the line.
) # End of the lookahead assertion.",
"[${before}|${after}]", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
这是完美的,正是我所需要的。我非常感谢所有解释它如何工作的评论。希望这会对其他尝试学习正则表达式的人有所帮助。谢谢你的帮助Tim。 – polara 2011-03-02 18:24:03
希望你可以试试这个正则表达式:/(\w[0-9]* *)+/g
这个过滤掉所有的字母数字除了。
对不起,但这是相当荒谬的。它与OP给出的例子都不匹配,但它确实匹配唯一编号的反例。当然,它根本不在乎引用的字符串...... – 2011-03-02 07:38:08
您无法提供足够的信息。 “隔离”是一个通用的和相对的术语,你不能通过向已经很模糊的条件添加条件来堆砌规范。更具体一些使用背景。 – sln 2011-03-01 02:02:47
我同意,我对你想达到的目标没有确定的想法。也许你可以说明你想要运行正则表达式的结果,也许还有你不想看到的结果(有时可能真的有用) – iain 2011-03-01 04:00:45
另外,你应该指定你正在使用的正则表达式引擎。有没有像'[Table.Name]。[Field.Name]'这样的结构,你只想在中点上分割? – 2011-03-01 07:53:10