Ewald Bos
Ewald Bos

Reputation: 1770

regex get word before character that is between other characters

I am trying to get the text from a css files, it's all the text that is before the : (overflow, white-space, width, margin-top) and make it blue

.MenuContainerScroll {
  overflow: auto;
  overflow-y: hidden;
  white-space: nowrap;
  width: 100%;
  margin-top: 1vw;
}

i am using the following regex:

html.replace(/(([A-z'-]+)\:)/g, '<span class="blue">$1</span>');

what works perfect, until it meets this:

.MenuContainerScroll::-webkit-scrollbar {
width: 6px;
height: 1vw;
}

now .MenuContainerScroll also turns blue, what i would like it to select every word before the : between the { } does that make sense? I get to select text between with

(/(\/\*(.*?)\*\/)/g

but i don't get how to combine these two, thanks

Upvotes: 1

Views: 47

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

You can prepend an anchor to assert the start of the string, match optional whitespace chars in group 1 ([^\S\r\n]*) before the character class, and capture the match from the character class ([A-Za-z'-]+:) in group 2.

^([^\S\r\n]*)([A-Za-z'-]+:)

Regex demo

In the replacement use

$1<span class="blue">$2</span>

If you want to assert a curly bracket before and after, you might also use lookarounds with an infinite quantifier in the positive lookbehind if that is supported.

(?<={[^{}]*)([^\S\r\n]*)([A-Za-z'-]+:)(?=[^{}]*})

Regex demo

Note that asserting the curly brackets does not take any nesting or balanced parenthesis into account and [A-z] matches more than [A-Za-z]

Upvotes: 3

Related Questions