Home > front end >  How to capture values with a space after hyphen with regex?
How to capture values with a space after hyphen with regex?

Time:10-06

I have some javascript code wherein I am trying to capture values from a string that match either of the following cases:

"-H" or "- H" (note the space in the second case)

I was able to capture the first case with the following regex:

(?=\S*['-])([a-zA-Z'-] )

However I can't seem to be able to figure out how to capture the case with the space in it.

This is an example of what I am trying to extract from. I am ONLY trying to capture the -H value. from this sentence:

This is non-refundable -H

CodePudding user response:

You can use

/\B-\s*[A-Z] \b/g

See the regex demo

Details:

  • \B - a non-word boundary (immediately on the left, there must be start of string or a non-word char)
  • - - a hyphen
  • \s* - zero or more whitespaces
  • [A-Z] - one or more ASCII uppercase letters
  • \b - a word boundary (immediately on the right, there must be end of string or a non-word char)

See the JavaScript demo:

const text = "-H - H\n-TEST - TEST";
const regex = /\B-\s*[A-Z] \b/g;
console.log(text.match(regex));

  • Related