J.Price
J.Price

Reputation: 15

Regular expression that only matches before space or no space

I'm trying to make global regular expression that matches every capitalised letter after ! but only before a space or no space, no lowercase letters.

For example:

!ABC <space> !XYZ <no space> should return: ABC XYZ

but !ABCtext <space>!XYZ<no space> should only return: XYZ

The code I have so far is:

const regex = /![A-Z]*\s/g;

Which returns capital letters after ! even if they are directly followed by more text, without a space.

Any help would be greatly appreciated.

Upvotes: 0

Views: 48

Answers (2)

The fourth bird
The fourth bird

Reputation: 163642

As @PJProudhon suggested, I think you could use !([A-Z]+)\b using a word boundary \b

([A-Z]+) will capture the capitalised letters after the ! in group 1.

const regex = /!([A-Z]+)\b/g;

Upvotes: 0

Mohammad Javad Noori
Mohammad Javad Noori

Reputation: 1227

What about ![A-Z]+(?=[^\w]|$)

Demo

Upvotes: 1

Related Questions