-1

I have a following regex which basically gets string with hyphens:

/class="(?=\S*[-])([a-zA-Z-]+)/gim

And the input string is:

<div class="hello-world h-123"></div>
<div class="this-is-cool"></div>

However, my problem is that in the input string, it only matches hello-world but I wanna match h-123 as well using same regex but separately (groups). Basically, I am trying to build a regex which basically gets all strings that contain dash.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Axel
  • 4,365
  • 11
  • 63
  • 122
  • 1
    https://stackoverflow.com/questions/4736/learning-regular-expressions – Derek Lawrence Oct 21 '19 at 16:33
  • [String.prototype.matchAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) – Anthony Oct 21 '19 at 16:34
  • Why are you using a lookahead? – Toto Oct 21 '19 at 16:36
  • 1
    Must you use regex for this? There are better methods for getting class names in javascript. – Sean Oct 21 '19 at 16:38
  • Are you expecting the final result to have three matches ("hello-world", "h-123", "this-is-cool") or two ("hello-world h-123", "this-is-cool")? – Dave K. Oct 21 '19 at 17:34
  • How are you obtaining those "div" strings? I agree with sean; if this is javascript running in a page with those divs, it would be better to get the classes from the dom elements themselves, rather than pattern-match the html strings. Fully parenthesized because of comment wrapping: `document.querySelectorAll('div').forEach(ex => { ex.classList.forEach(c => { console.log( c + ' includes dash? ' + c.includes('-') ); } ); } );` … and the obligatory link to [Don't Parse HTML with Regex](https://stackoverflow.com/questions/1732348) – Stephen P Oct 21 '19 at 22:05

2 Answers2

2

Your RegExp specify starting with class=" and contains only letters. Change it to be letters and numbers (I've used \w which contains letters, numbers, and underscores) with at least one dash between them:

const regexp = /\w+(-\w+)+/gim
const str = `<div class="hello-world h-123"></div>
<div class="this-is-cool"></div>`

const result = str.match(regexp)

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

([\w\s]*[-][\w]*)*

This will look for any string that starts with a alphanumeric character or space, has a hyphen, and is followed by a alphanumeric character. It does this multiple times to link together hyphenated phrases that may have a space between the first and most recent one.

Dave K.
  • 258
  • 1
  • 10