简体   繁体   English

RegEx用于前缀/未加前缀的字符串

[英]RegEx for prefixed/unprefixed string

I'm trying to perform a conversion on my XML string by detecting a tag that's always like this: 我正在尝试通过检测始终如下的标记来对我的XML字符串执行转换:

<attr name="firstName" />
<attr name="Name" />
<attr name="lastName" />

I wish to catch it and replace it by itself with a suffix so I'll get this: 我希望抓住它并用后缀替换它,所以我会得到这个:

<attr name="firstName" /><attr name="beep" />
<attr name="Name" /><attr name="beep" />

But if it's the last one, I wish not to do anything at all. 但如果是最后一个,我希望不要做任何事情。

<attr name="lastName" />

I'm trying with this detection pattern. 我正在尝试这种检测模式。

Regex.Replace(before, "(<attr name=\"[first]*name\" />)", "[0]<attr name=\"beep\" />");

But this will match all permutations of first . 但这将匹配第一个的所有排列。 How can I express at most one of the exact string "first" ? 我怎样才能最多表达一个确切的字符串“first”

Regex.Replace(before, "(<attr name=\"[first]?name\" />)", "$0<attr name=\"beep\" />");

Replacing the * with a ? ?替换* will search for either one or zero occurences. 将搜索一个或零个出现。

I suggest using a negative lookahead: 我建议使用否定前瞻:

Regex.Replace(before, "(<attr name=\"(?!last)[^\"]*Name\" />)", "$0<attr name=\"beep\" />");

To detect zero or one of the string "first", then you can simply change the lookbehind into a normal group that is optional, and replace "last" with "first". 要检测字符串“first”中的零个或一个,则可以简单地将lookbehind更改为可选的普通组,并将“last”替换为“first”。

Regex.Replace(before, "(<attr name=\"(?:first)?Name\" />)", "$0<attr name=\"beep\" />");

I think what you want is: 我想你想要的是:

Regex.Replace(before, "(<attr name=\"(?:first)?name\" />)", "$0<attr name=\"beep\" />");

[first] in a regular expression says "any of the characters f , i , r , s or t ". [first]在正则表达式中写着“任何字符first ”。

(?:first) says "the string of characters first , treated as a (non-capturing) group". (?:first)表示“字符的字符串first ,作为(非捕获)处理的组”。 ? then says that the preceeding match should occur zero or one time. 然后说先前的匹配应该发生零次或一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM