Regex catch from the hash sign "#" to the next white space

I have a script line this :

#type1 this is the text of the note

I've tried this bu didn't workout for me :

^\#([^\s]+)

I watch to catch type in other words I to get whats between the hash sign "#" and the next white space, excluding the hash "#" sign, and the string that I want to catch is alphanumeric string.

Upvotes: 1

Views: 1096

Answers (4)

I've figured it out.

/^\#([^\s]+)+(.*)$/

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163267

To get an alphanumeric match (which will get you type1), instead of the negated character class [^\s] which matches not a whitespace character, you could use a character class and specify what you want to match like [A-Za-z0-9].

Then use a negative lookahead to assert what is on the right is not a non-whitespace char:

^#([A-Za-z0-9]+)(?!\S)

Regex demo

Your match is in the first capturing group. Note that you don't have to escape the \#

For example using the case insensitive flag /i

const regex = /^#([A-Za-z0-9]+)(?!\S)/i;
const str = `#type1 this is the text of the note`;
console.log(str.match(regex)[1]);

If you only want to match type, you might use:

^#([a-z]+)[a-z0-9]*(?!\S)

Regex demo

const regex = /^#([a-z]+)[a-z0-9]*(?!\S)/i;
const str = `#type1 this is the text of the note`;
console.log(str.match(regex)[1]);

Upvotes: 0

SoKeT
SoKeT

Reputation: 610

You're really close:

/^\#(\w+)\s/

The \w matches any letters or numbers (and underscores too). And the space should be outside the matching group since I guess you don't want to capture it.

Upvotes: 0

Bi Ao
Bi Ao

Reputation: 894

With the regex functionality provided by Javascript:

exec_result = /#(\w*)/.exec('#whatever string comes here');

I believe exec_result[1] should be the string you want.

The return value of exec() method could be found over here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Upvotes: 1

Related Questions