首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在emacs中匹配regexp和分组

在emacs中匹配regexp和分组
EN

Stack Overflow用户
提问于 2009-06-08 14:36:19
回答 3查看 2.4K关注 0票数 1

我尝试匹配一个字符串,然后使用grouping创建一个新的字符串:

代码语言:javascript
复制
  (let ((url (browse-url-url-at-point)))
    (if (string-match "http://domain/\\([0-9]+\\)/\\([a-z]+\\)\.\\([0-9]+\\)" url)
  (setq filename (concat (match-string 1 url) "_" (match-string 2) "." (match-string 3) ".xml"))))

当我(打印url)时,我得到以下信息

代码语言:javascript
复制
"http://domain/1234/action.1234567"

在成功匹配后,当I(打印文件名)时,我得到以下内容:

代码语言:javascript
复制
#("1234_ublish.eport s.xml" 0 5 nil 5 11 (face nxml-element-local-name-face fontified t) 11 12 nil 12 17 (face nxml-element-local-name-face fontified t) 17 18 (fontified t) 18 19 (face nxml-attribute-local-name-face fontified t) 19 23 nil)

为什么会发生这种情况?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-06-08 14:57:01

您的第二个和第三个匹配字符串没有包含可选的字符串参数。根据匹配字符串文档,“如果最后一次搜索是通过字符串上的‘string -match’进行的,则应提供字符串。”

票数 4
EN

Stack Overflow用户

发布于 2009-06-08 14:59:30

我找到问题了。

原来( string -match)需要将原始字符串作为参数,否则它将返回包含奇怪值的奇怪列表(不确定这些值是什么)。

无论如何,将关于代码更改为:

代码语言:javascript
复制
 (let ((url (browse-url-url-at-point)))
    (if (string-match "http://domain/\\([0-9]+\\)/\\([a-z]+\\)\.\\([0-9]+\\)" url)
  (setq filename (concat (match-string 1 url) "_" (match-string 2 url) "." (match-string 3 url) ".xml"))))

修复问题

票数 3
EN

Stack Overflow用户

发布于 2009-06-08 19:07:10

作为mamboking already mentionedmatch-string的文档字符串告诉您有关以下内容的所有信息:

代码语言:javascript
复制
(match-string NUM &optional STRING)
 ⋮
STRING should be given if the last search was by `string-match' on STRING.

如果你还查看了string-match的文档,你会发现它建议使用match-beginningmatch-end来获取匹配,这些都是C中的内置函数。

代码语言:javascript
复制
(if (string-match "\\([a-z]\\)" "123 test string")
  (match-beginning 1)) ;; 4

这些函数只返回匹配文本的开始或结束位置,这就是为什么match-string也需要原始字符串的原因。当使用search-forwardre-search-forward时,match-beginningmatch-end将返回缓冲区位置,因此match-string可以很容易地从缓冲区的内容中子串有趣的匹配。

您可能还想看看match-string-no-properties,它的行为与match-string相同,期望它返回没有文本属性的匹配文本字符串。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/965193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档