简体   繁体   English

正则表达式仅匹配第一个标签

[英]Regex to match only the first tag

I am trying to write a regex to find a selection in one long string of xml, and pull out the first instance of a tag it finds. 我正在尝试编写一个正则表达式以在xml长字符串中找到一个选择,然后拉出它找到的标签的第一个实例。

My current code (which pulls out every match): (<action>(.*?)</action>) 我当前的代码(每次匹配都会退出): (<action>(.*?)</action>)

Sample code: 样例代码:

<request guid="58004a1e-0c32-4002-a101-59fc28af5836">
<action>Sample/Action</action><date>"7/12/12"</date>

I have tried using multiple ways I have found to either match the first instance and disregard everything else, check and make sure there is no match before the current match, set it to match exactly one, etc. but they all return two matches. 我尝试使用多种方法来找到匹配第一个实例并忽略其他所有内容,检查并确保当前匹配之前没有匹配项,将其设置为完全匹配一个,依此类推,但是它们都返回两个匹配项。 I am unable to set the regex to look for a particular leading or trailing tag as those can change. 我无法设置正则表达式来查找特定的前导或尾随标记,因为它们可能会更改。

Simple answer: stop. 简单的答案:停下来。

You're asking the wrong question, because you've decided you're going to use regular expressions to solve your problem before working out whether regular expressions are an appropriate way to solve your problem. 您问的是错误的问题,因为您已经确定在确定正则表达式是否是解决问题的适当方法之前,将使用正则表达式来解决问题。

Both C# and Java have XML parsing libraries, and you'd be much better off using one of those, rather than trying to duplicate their functionality using regular expressions, a task which is in general impossible, as XML is not a regular language. C#和Java都具有XML解析库,因此最好使用其中之一,而不是尝试使用正则表达式来复制其功能,这通常是不可能的,因为XML不是正则语言。

See also this answer , although that question was about HTML. 另请参阅此答案 ,尽管该问题与HTML有关。

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

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