Capturing a word in front of a specific character

I need to create a javascript regex that will capture the "word" that precedes the single or double :

.

Here are some examples:

*, ::before, ::after // do not capture anything
.class1, .class2:before,.class3::after // captures .class2 and .class3
.class4::before // captures .class4

      

This is what I have right now: /(\S+?):/g

. It matches any non-white space symbol from one to infinity times several times and then stops at :

.

This works except:

  • If there is no space before the word, it grabs too far.
  • It captures the first colon ::before

    and ::after

    .
+1


source to share


2 answers


You can use this regex:

 ([.\w]+):?:\w+

      

Working demo

enter image description here



As you need this regex:

([.\w]+)      Captures alphanumeric and dots strings before
:?:\w+        one or two colons followed with some alphanumeric

      

Match info:

MATCH 1
1.  [57-64] `.class2`
MATCH 2
1.  [72-79] `.class3`
MATCH 3
1.  [119-126]   `.class4`

      

0


source


Just add extra / optional :

at the end:

/(\S+?)::?/g

      

Or you can specify it as repeating 1-2 times:



/(\S+?):{1,2}/g

      

Demo

0


source







All Articles