正则表达式最后选择除字符串之外的所有字符串

时间:2014-01-05 09:17:27

标签: regex

我希望正则表达式选择除“html”字符串之外的所有字符串 如果找不到“html”,则选择完整字符串:例如:this string

  

yurry / NOVA-GTA-花-HTML-中将Html.HTML

  

yurry / NOVA-GTA-flowers.html

^([^/]*)/(.*?).(?=html)这个选择yurry / nova-gta-flowers

我创建这个正则表达式正常工作选择除html字符串之外的所有字符串到最后 我的问题是,如果没有“html”字符串,这将导致我的正则表达式不选择完整的字符串,例如:

  

yurry / NOVA-GTA-花
   我的正则表达式没有选择

3 个答案:

答案 0 :(得分:2)

我会建议:

^([^/]*)/(.*?)(\Whtml)*$

<强>说明:

^       # Match the start of the string
([^/]*) # Match any number of non-slash characters --> group 1
/       # Match a slash
(.*?)   # Match any characters, as few as possible --> group 2
(?:     # Match but don't capture...
 \W     #  one non-alphanumeric character (like . or -)
 html   #  "html"
)*      # any number of times, including zero
$       # Match the end of the string

答案 1 :(得分:0)

第一个错误,html之前的点必须被转义。

最后一个块必须是optionnal,包括点。

^([^/]*)/(.*?)(\.html)?

但检查字符串是否以.html结尾并在需要时删除它会更简单。

答案 2 :(得分:0)

您可以使用此正则表达式:

^([^/]*)/((?:.(?!html))*)

regex101 demo

(?:.(?!html))*将匹配除html之外的任何字符,并保留最后一个字符。