【问题标题】:Regex to Remove Special characters and Spaces and Then Camel Case It正则表达式删除特殊字符和空格,然后驼峰式它
【发布时间】:2014-10-23 15:51:13
【问题描述】:

我正在尝试使用正则表达式生成 C# 属性。我有 100 多个,而且任务可能会重复,所以值得付出努力。

要转换的字符串:

Do you own your property?
How is it owned?
Relationship to other registered owner
Estimated value of Estate (joint)
Address Line 1
Are any of the children under 18 years old?
Are you interested in safeguarding your assets for your children/beneficiaries?

预期结果:

public string DoYouOwnYourProperty { get; set;}
public string HowIsItOwned { get; set;}
public string RelationshipToOtherRegisteredOwner { get; set;}
public string EstimatedValueOfEstateJoint { get; set;}
public string AddressLine1 { get; set;}
public string AreAnyOfTheChildrenUnder18YearsOld { get; set;}
public string AreYouInterestedInSafeguardingYourAssetsForYourChildrenBeneficiaries { get; set;}

我四处打听,发现they would remove special charswould UpperCase it in code 的正则表达式问题的味道,但不能同时使用正则表达式。

started out with this

([a-zA-z])( [a-zA-z])([a-zA-z])

替换:

\1\U2\3

但是第 2 组没有大写,我不确定如何为所有内容而不是每个组附加 public string{ get; set;}

【问题讨论】:

  • 大写不是“标准”正则表达式操作,它取决于工具。你在用什么?
  • @LucasTrzesniewski 开发正则表达式我使用 101regex,替换我打算使用 notepad++。

标签: regex


【解决方案1】:

在记事本++中:

第 1 步:删除标点符号

替换以下模式:

[^\w\s]

使用空字符串。

第 2 步:删除空格并将字母变为大写

替换以下模式:

[^\S\r\n]+(\d*\p{L}|\d+)

有了这个:

\U$1

第 3 步:添加属性语法

替换以下模式:

^(\S+)$

有了这个:

public string $1 { get; set; }

作为参考,以下是 Notepad++ 用于正则表达式替换的内容:Boost-Extended Format String Syntax

【讨论】:

  • 您好,在很多情况下确实会失败,属性中的数字就是其中之一。 Recipient Surname Recipient Title Address Line 1 Address Line 2 Address Line 3 Address Line 4 Address Line 5 Address Line 6 Post Code
  • 糟糕,我没有考虑数字。我已经修改了模式,它们应该可以工作
  • 在单个案例 Estimated value of Estate (joint) 上使用了 100+ 个。还有一个案例可以手工完成,谢谢伙计。
  • 我颠倒了前两个步骤,所以它现在应该适用于你的最后一个案例
  • 完美运行,真正的专业人士。谢谢。
【解决方案2】:

您不能使用 regex101.com,因为它的可访问引擎不支持 \U\L 替换令牌。不过记事本++没问题。

首先,使用此正则表达式来匹配这些空格/标点符号及其以下字符:

[^[:alnum:]\n\r](\w)?

替换为

\U$1

第二,匹配最近的整行:

^(?i)([a-z\d]+)$

并替换为:

public string $1 { get; set;}

【讨论】:

  • 您好,没有处理带数字的案件。 Executor Title Address Line 1 Address Line 2 Address Line 3 Address Line 4 Address Line 5 Address Line 6 Post Code Home Phone Number Mobile Number Email Notes to solicitor Are any of the children under 18 years old? Do you have executor(s)?
  • 更新后[^[:alnum:]\n\r]\d*(\w)? 删除产生 6 x AddressLine 而末尾没有数字的数字(地址行 1 和地址行 2 是两个不同的属性)
  • @LIUFA 我回滚了第一个正则表达式,修改了第二个。检查更新。
  • 完美运行,非常感谢。我已经接受了其他答案,因为@Lucas 是第一个,但我给了你相同数量的代表 + 你的其他答案。
猜你喜欢
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 2011-10-16
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多