微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何支持将此正则表达式从JAVA转换为C#?

如何解决如何支持将此正则表达式从JAVA转换为C#?

我用Java开发了一个应用程序,现在需要将其转移到C#(UWP)。我需要转换以下正则表达式,但C#不支持所有格限定符,因此“?+”部分会使正则表达式对象崩溃。 (其余的似乎工作正常)

正则表达式:(?<!({0})(?:({1}))?)(?:({2}))?\b({3})(e?s|x)?\b(?:\s({4})[sx]?)?+(?!(\s{5}))

该表达式是根据用户输入动态构建的。

Parts: 
 - {0}: exclude prefix 
 - {1}: include prefix
 - {2}: include prefix
 - {3}: include expression (is the word to find)
 - {4}: include suffix
 - {5}: exclude suffix
Logic: 
 - Find the word `{3}`.
 - Join the "include" prefix `{1}` & `{2}`,if presents,to the found
   word.
 - Join the "include" suffix `{4}`,if present,to the found word.
 - Don't match anything if the word (even if preceeded by the "include"
   prefix) is preceeded by the "exclude" prefix `{0}`.
 - Don't match anything if the word (even if followed by the "include"
   suffix) is followed by the "exclude" suffix `{5}`.

具体示例:(?<!({la})(?:({petite}))?)(?:({petite}))?\b({maison})(e?s|x)?\b(?:\s({bleu})[sx]?)?+(?!(\s{ciel}))

Should match:
 - maison
 - petite maison
 - maison bleue
 - petite maison bleue

Should not match:
 - la maison
 - maison ciel
 - la petite maison
 - maison bleue ciel
 - la petite maison bleue
 - petite maison bleue ciel
 - la maison bleue ciel
 - la petite maison ciel
 - la maison ciel
 - la petite maison bleue ciel

如果有建议,可以更改表达式,但需要给出相同的结果。

注意:我尝试了PCRE.NET Nuget,但似乎又产生了一个带有lookbehind表达式的问题(lookbehind断言在偏移量0处不是固定长度)。

所以...有人可以帮我吗?

解决方法

您可以使用原子组:

(?<!\bla\s+(?:petite\s+)?)(?:petite\s+)?(?>maison(?:e?s|x)?\b(?:\s+bleu[sxe]?)?)(?!\s+ciel)

请参见.NET regex demo

详细信息

  • (?<!\bla\s+(?:petite\s+)?)-字符串中不直接包含完整单词la\b是单词边界)的位置,后跟1+空格和{{1}的可选序列}和1+空格
  • petite-可选的(?:petite\s+)?和1+个空格序列
  • petite-此处,一个与(?>maison(?:e?s|x)?\b(?:\s+bleu[sxe]?)?)匹配的原子组,然后是可选maison的可选序列,后跟es,然后是单词边界,然后是1+空格和x的可选序列,后跟1或0 bleus或{ {1}}
  • x-后面没有1+空格和e

请参见C#演示

(?!\s+ciel)

输出:

ciel

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?