c# - 为什么我的 RegEx 会根据平台得到两个不同的结果?

标签 c# .net regex

我有一个 RegEx 模式:

@"((?(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

旨在将字符串分成 3 部分。如果我有琴弦

"asdf1234asdf"
"asdf .1234asdf"
"asdf. .1234asdf"
"asdf 12.34asdf"
"asdf123.4 asdf"
"asdf.1234asdf"

我需要:

1. "asdf"     2. "1234"    3. "asdf"
1. "asdf "    2. ".1234"   3. "asdf"
1. "asdf. "   2. ".1234"   3. "asdf"
1. "asdf "    2. "12.34"   3. "asdf"
1. "asdf"     2. "123.4"   3. " asdf"
1. "asdf"     2. ".1234"   3. "asdf"

但根据我使用的平台,结果会发生变化。

Regex101.com gives me the results i need

though in Regexstorm.com i have to modify the if statement in the Regex to a non-capturing group for it to work

即:我需要将其更改为

@"((?(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

@"((?:(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

让它在 .NET 中工作

那么为什么我需要去掉“if” block 呢? .NET 不支持 if block 吗?

最佳答案

与 C# 相比,RegEx 更类似于英语。它是一种用于定义模式的语言,可以在字符串中找到匹配项。每种语言都需要实现它们的正则表达式引擎,因此大多数语言之间存在差异,但概念基本相同。通常,表达式越复杂,就越有可能不跨平台兼容。这就是为什么当被问到一个模糊的 RegEx 问题时,每个人都会问 SO 用户他们使用什么编程语言。

这就是为什么像 RegEx101 这样的工具需要有多种“口味”来彻底测试表达式。您还会注意到“快速引用”内容(包含标记、量词等的备忘单)随着引擎之间的变化而变化。

维基百科: Comparison of regular expression engines.

关于c# - 为什么我的 RegEx 会根据平台得到两个不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32255963/

相关文章:

c# - 如何将 Bloomberg DateTime 转换为 System.DateTime

C# XAML Metro 图​​像动态源

.net - 无法找到入口点 (cpp)

javascript - 不使用后向匹配此字符串 - Javascript Regex

c# - 解析电子邮件地址字符串的最佳方法

.net - NewtonSoft Json Assembly 版本问题

.net Ajax calendarExtender 在 IE7 中削减星期六(在 firefox 中工作正常)

regex - 将 `"`引号改成latex风格

javascript - 如何替换文本框中的逗号?

C# HttpClient.SendAsync 在测试某些 URL 时抛出 "An error occurred while sending the request"异常