Rob Graham
Rob Graham

Reputation: 73

Regex match partial word with nothing before but spaces allowed

I want to match some class names in a string that start with row- but it can't allow characters before the match, except space.

I've used /row-/g and /\s?row-/g and word boundaries but the problem arises when the user could possibly use a class name with foo-borrow-bar where the row- in borrow returns a match or some-row-class.

My example string of class names i'm testing against:

row-some-class foobar hello-world-row-class foo-borrow-bar row-it-is

I only want to match row-some-class and row-it-is

Upvotes: 1

Views: 4845

Answers (3)

Božo Stojković
Božo Stojković

Reputation: 2943

You can try this regex:

(:?^|\s)row-

You can either have "row-" at start of the line or in front of whitespace in order for it to be valid.

(:? # Non-capturing group
    ^|\s # Matches tart of string/line or whitespace
)row-

Upvotes: 3

guest271314
guest271314

Reputation: 1

You can use .match() with RegExp /row-\w+-\w+/(?=\s|$)/g to match row- followed by word followed by - followed by word if followed by space character or end of input

console.log(
  "row-some-class foobar hello-world-row foo-borrow-bar row-it-is"
  .match(/row-\w+-\w+(?=\s|$)/g)
)

Upvotes: 0

heemayl
heemayl

Reputation: 42147

You can surround the pattern using word boundaries, \b:

\b ?row-\b

Also note that, \s is not just space, its actually

[ \t\n\r\f\v]

so unless you are sure about the input, better be explicit to avoid unexpected results.

Demo

Upvotes: 0

Related Questions