.net正则表达式-最后一个列表项中不包含句号的字符串

我正在尝试使用.net正则表达式来标识XML数据中的字符串,这些字符串在最后一个标记之前不包含句号。我对正则表达式没有太多经验。我不确定我需要更改什么以及为什么要获得想要的结果。

数据中每行的末尾都有换行符和回车符。

模式用于XML。

优质XML数据示例:

const int Nsides;

错误的XML数据示例-regexp应该匹配-最后一个<randlist prefix="unorder"> <item>abc</item> <item>abc</item> <item>abc.</item> </randlist> 前没有句号:

</item>

我尝试的Reg exp模式在不良XML数据中不起作用(未经良好XML数据测试):

<randlist prefix="unorder">
    <item>abc</item>
    <item>abc</item>
    <item>abc</item>
</randlist>

使用http://regexstorm.net/tester的结果:

^<randlist \w*=[\S\s]*\.*[^.]<\/item>[\n]*<\/randlist>$

使用https://regex101.com/的结果:

0 matches

此问题与以下imo不同,原因是字符串条件已完全停止和开始:

Regex for string not ending with given suffix

3的解释:

0 matches
a123123aaaaa 回答:.net正则表达式-最后一个列表项中不包含句号的字符串

@Silvanas是绝对正确的。您不应该使用Regex解决此问题,而应使用某种形式的XML解析器读取数据并使用.查找行。但是,如果出于某种可怕的原因必须使用Regex,并且如果数据的结构与示例完全相同,则Regex解决方案如下:

^\s+<item>[^<]*?(?<=\.)<\/item>$

如果与该正则表达式有任何匹配,则您的xml格式不正确。但是同样,如果空格不正确,行上还有其他内容,标签arent <item>..</item>等,则此正则表达式也会失败。同样,除非您可以绝对保证.以外的所有格式都将采用格式正确的XML

,否则不使用Regex解决此问题将远为好得多。

编辑:如果开始和结束标记在同一行上,但不一定标题为“ item”,并且可能具有属性,请继续尝试以下操作:

^\s+<([^<>\s]+)[^<>]*>[^<>]*?(?<=\.)<\/\1>$

Breakdown:
^           anchor to beginning of line
\s+         skip over any whitespace
<           found what looks like an opening tag
([^[]\s]+)  match the first word found after the "<",store in capture group 1
[^<>]*>     match whatever remain until the closing ">"
[^<>]*?     match all of the contents up until the next "<"
(?<=\.)     ensure the last character was a "."
<\/\1>      match a closing tag where the text after the / is the same as the first word of the opening tag (stored in capture group 1)
$           anchor to end of line

确保设置了MultiLine regex选项,否则^和$将匹配整个字符串的开头/结尾。与以前一样,与此正则表达式的任何匹配都意味着XML在该行上的格式不佳。

本文链接:https://www.f2er.com/2737174.html

大家都在问