将哈希字符 (#) 与正则表达式匹配 [英] Matching a hash character (#) with a regex
问题描述
我有一个包含正则表达式的 XML 文档(所以你不需要用 \ 转义).基本上我试图匹配音乐和弦符号,这个正则表达式工作正常,但拒绝匹配哈希:
I have an XML document that contains a regular expression (so you don't need to escape with \). Basically I'm trying to match musical chord symbols, and this regex works fine, but refuses to match a hash:
\b[A-G](m|b|\#|sus|\d)*?\b
推荐答案
问题是词边界锚\b
只匹配字母数字和非字母数字字符,所以不会't 在 #
之后匹配(除非它本身后跟一个字母数字).
The problem is that \b
, the word boundary anchor, only matches between alphanumeric and non-alphanumeric characters, so it won't match after a #
(unless that is itself followed by an alphanumeric).
使用
\b[A-G](?:m|b|#|sus|\d)*(?:\b|(?<=#))
也不需要转义 #
.
更改正则表达式以更好地重现预期功能(我认为应该如此)
Changed the regex to better reproduce the intended functionality (as I think it should be)
目前,您没有匹配一些和弦;怎么样
Currently, you're not matching some chords, though; how about
\b[A-G](?:add|maj|j|m|-|b|#|sus|\d|°)*(?:\b|(?<=[#°-]))
这样,您就可以匹配所有这些:
That way, you can match all of these:
A7
Abm7
A#m7sus4
A7b9#13
Amaj7#11
A#°
Abj7add13
不过,我想仍有改进的空间.
I guess there is still room for improvement, though.
这篇关于将哈希字符 (#) 与正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!