Match hash character (#) with regex

I have an XML document that contains a regular expression (so you don't need to escape with \). Basically I try to match musical chord characters, and this regex works fine, but refuses to match the hash:

\b[AG](m|b|\#|sus|\d)*?\b 
+4
source share
1 answer

The problem is that \b , the word boundary anchor, matches only alphanumeric and non-alphanumeric characters, so it won’t match after # (unless it is followed by an alphanumeric expression).

Use

 \b[AG](?:m|b|#|sus|\d)*(?:\b|(?<=#)) 

No need to avoid # either.

EDIT: Regular expression changed to better reproduce the intended functionality (as I think it should be)

Currently, you do not agree with some chords; What about

 \b[AG](?:add|maj|j|m|-|b|#|sus|\d|Β°)*(?:\b|(?<=[#Β°-])) 

Thus, you can map all of them:

 A7 Abm7 A#m7sus4 A7b9#13 Amaj7#11 A#Β° Abj7add13 

I think there is still room for improvement.

+7
source

Source: https://habr.com/ru/post/1338235/


All Articles