如何使用^和$解析简单表达式?

2024-09-27 04:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用^$符号来只解析下面的/blog/articles?你知道吗

我创建了包含以下内容的ex3.txt:

/blog/article/1 
/blog/articles 
/blog 
/admin/blog/articles

还有正则表达式:

^/blog/articles$

似乎不起作用,因为当我使用'regetron'(see learning regex the hard way)键入时,下一行没有输出。你知道吗

这是我的确切程序:

  1. 在正确目录的命令行中,我键入:regetron ex3.txt。ex3.txt包含一行,其中包含以下内容:

    /blog/article/1/blog/articles/blog/admin/blog/articles

虽然我试过在条目之间用换行符。你知道吗

  1. 我输入^/blog/article/[0-9]$,下一行不返回任何内容。

  2. 我尝试了发布的第一个解决方案,^\/blog\/articles$,但没有返回任何结果。

提前谢谢SOers!你知道吗


Tags: thetxt键入adminarticle符号blogarticles
2条回答

将正则表达式更改为:

^\/blog\/articles$

你需要摆脱你的割伤。你知道吗

另外,确保ex3.txt文件中每一行的末尾都没有尾随空格。你知道吗

根据您的更新,听起来^$可能不是适合您的运算符。它们分别匹配一行的开始和结束。如果要在同一行中匹配多个字符串,则需要类似以下内容:

(?:^|\s)(\/blog\/articles)(?:$|\s)

它的作用是:

(?:^|\s)            Matches, but does not capture (?:), a line start (^) OR (|) a whitespace (\s)
(\/blog\/articles)  Matches and captures /blog/articles.
(?:$|\s)            Matches, but does not capture (?:), a line end ($) OR (|) a whitespace (\s)

这对这两种情况都有效,但请注意,它将在/blog/articles前后匹配(但不会捕获)一个空格。你知道吗

相关问题 更多 >

    热门问题