从字符到行尾匹配正则表达式,但忽略最后一个字符

时间:2022-07-05 15:23:58

The regex

正则表达式

(file\..*$)

matches "file.xml" correctly in

匹配”文件。xml“正确

$cd = "..\folder\file.xml"

but I'd like to ignore the trailing quote via regex if possible

但是,如果可能的话,我想通过regex忽略后面的引用。

3 个解决方案

#1


1  

You could say: anything not a ":

你可以说:“任何事都可以”。

(file\.[^"]*)"$

See a demo on regex101.com.

请参阅regex101.com上的演示。


In your example, you do not even need the anchors:

(file\.[^"]*)

#2


1  

You can update your regular expression to the following:

您可以将正则表达式更新为以下内容:

(file\..*?)"?$

That'll make sure that if there is a trailing quote it will not be captured.

这将确保如果有一个尾引号,它将不会被捕获。

#3


0  

Move the last char along with the end marker out of the group:

将最后一个字符和结束标记一起移出组:

(file\..*).$

https://regex101.com/r/bZ7vV5/1

https://regex101.com/r/bZ7vV5/1

Or if you may have a non-quote last char which you would like to capture instead, then specify this quote explicitly but as optional ("?) and make the previous match non-greedy (.*?):

或者,如果您希望捕获一个非引号的最后一个字符,那么显式地指定这个引号,但作为可选的(“?”),并使先前的匹配不贪婪(.*?):

(file\..*?)"?$

https://regex101.com/r/bZ7vV5/3

https://regex101.com/r/bZ7vV5/3

#1


1  

You could say: anything not a ":

你可以说:“任何事都可以”。

(file\.[^"]*)"$

See a demo on regex101.com.

请参阅regex101.com上的演示。


In your example, you do not even need the anchors:

(file\.[^"]*)

#2


1  

You can update your regular expression to the following:

您可以将正则表达式更新为以下内容:

(file\..*?)"?$

That'll make sure that if there is a trailing quote it will not be captured.

这将确保如果有一个尾引号,它将不会被捕获。

#3


0  

Move the last char along with the end marker out of the group:

将最后一个字符和结束标记一起移出组:

(file\..*).$

https://regex101.com/r/bZ7vV5/1

https://regex101.com/r/bZ7vV5/1

Or if you may have a non-quote last char which you would like to capture instead, then specify this quote explicitly but as optional ("?) and make the previous match non-greedy (.*?):

或者,如果您希望捕获一个非引号的最后一个字符,那么显式地指定这个引号,但作为可选的(“?”),并使先前的匹配不贪婪(.*?):

(file\..*?)"?$

https://regex101.com/r/bZ7vV5/3

https://regex101.com/r/bZ7vV5/3