Nict
Nict

Reputation: 3098

Regular expression matching hashtag, whitespace then characters

Ok, so I've been reading up on regexes, and they're fun!

I've been looking into matching a string like # 54jsfjk or # ffskkkkkkkkkkkkkkkkk884587923572957

Will the following suffice: /# \w*/i?

The string I'm trying to replace lives on a single line (there are more lines after), so I guess matching everything after isn't good.

Would making use of the ^ and $ only choose the single line?

The file I am working with looks sort of like this:

HEADER

# stringthatsreplaced

OTHER HEADER
- Stuff
- More Stuff

ANOTHER HEADER
- Even more stuff
- Last stuff

Upvotes: 0

Views: 307

Answers (1)

Jerry
Jerry

Reputation: 71578

If you want to use the anchors, you need to use the multiline mode as well:

/^# \w*$/m

*As rightly pointed out by Robin in the comment, the case insensitive flag isn't required here as \w is already case insensitive. It doesn't hurt to use it, but it's not doing anything in this particular regex.

Otherwise, ^ and $ will match only at the beginning of the file/text block (not line) and $ will match only at the end of the file/text block.

And I'm not sure if you can have spaces as well, or other characters, but if you do, you will need to use something else than \w*. .* should be working just as fine to match the whole line that begins with #:

/^# .*$/m

Upvotes: 1

Related Questions