如果源字符串不以相同的子字符串开头,则在前面添加一个子字符串
我正在尝试创建一个有效的 RegEx 替换模式来正确格式化特定的 .XML 文件名。具体来说,如果文件名不以前缀开头,例如 ACE_。如果 XML 文件名和扩展名不以 ACE_ 开头,请在文件名前面添加字符串 ACE_。例如,如果我的输入源字符串如下:
Widgets.xml
我想执行一个正则表达式替换,这将导致字符串为:
ACE_Widgets.xml。
相反,如果字符串已经以 ACE_ 开头,我希望它保持不变。
另外,如何包含模式“.xml”以确保文件名和扩展名的字符串模式以“.xml”结尾,与正则表达式替换模式的匹配模式相同?
至于匹配,我有一些运气:
^ACE_{1}[\d\D]+
如果输入字符串是 ACE_Widgets.xml,则表明该模式有匹配项;如果输入字符串是 Widgets.xml,则表明没有匹配
项 RegEx 模式就足够了,但如果您需要要知道我想使用替换模式的语言是 C# 或 VB.NET 中的 .NET 4.0。
下面的帖子与我正在寻找的内容很接近,但是由于包含了 *ix 目录路径前缀,并且在 PHP 中使用了 preg_replace(),我在让它与什么一起工作时遇到了一些困难我需要这样做:
一如既往,提前感谢您的时间、帮助和耐心。他们非常感激……
I’m trying to create a valid RegEx replacement pattern for correctly formatting specific .XML file names. Specifically, if a file name does not begin with a prefix, let’s say, ACE_. If the XML file name and extension does not begin with ACE_, prepend the string ACE_ to the file name. For example, if my input source string is the following:
Widgets.xml
I would like to execute a single RegEx Replacement that would result in the string being:
ACE_Widgets.xml.
Conversely, if the string already begins with ACE_, I would like it to remain unchanged.
Also, how can I include the pattern “.xml” to ensure that the string pattern for the file name and extension ends with “.xml” in the same matching pattern for the RegEx Replacement pattern?
As for the match, I have some luck with the following:
^ACE_{1}[\d\D]+
Which indicates there is a match for the pattern if the input string is ACE_Widgets.xml and no match if the string is Widgets.xml
The RegEx pattern would suffice, but if you need to know the language in which I’d like to use the replacement pattern is in .NET 4.0 in either C# or VB.NET.
The following posting is close to what I’m looking for, but with the inclusion of the *ix directory path prefix, and the use of preg_replace() in PHP, I’m having a bit of a struggle getting it to work with what I need to do:
Regular Expression: How to replace a string that does NOT start with something?
As always, thank you in advance for your time, help and patience. They are very much appreciated…
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上,正则表达式是完成此任务的一种非常干净的方法。以下是一个以自由间距模式编写的正则表达式的解决方案,其中包含大量 o 注释:
请注意,这假设
ACE_
前缀要求区分大小写。Actually regex is a pretty clean way to accomplish this. Here is a solution with a regex written in free-spacing mode with lots-o comments:
Note that this assumes that the
ACE_
prefix requirement is case sensitive.这里不需要正则表达式:
如果您也想添加对 .xml 扩展名的检查,请添加:
There is no need for regex here:
If you want to add checking for the .xml extension too, add:
如果 RegExp 不是特定要求,我建议您使用 String.StartsWith( ) 功能相反,因为它读起来更自然。
If RegExp is not a specific requirement I suggest you use String.StartsWith() function instead, as it reads more naturally.
这些天在 c#6
And these days in c#6