kiwi1342
kiwi1342

Reputation: 1389

Regular expression match any character at the beginning end with specific string

I have the following string:

"bar foo test-line drop-line"

I need to replace the words that starts with anything and ends with '-line'.

basically having:

"bar foo new_word new_word"

I tried:

string.replace(/\.-line$/g,'new_word')

but it doesn't work.

Upvotes: 0

Views: 1200

Answers (3)

vcarel
vcarel

Reputation: 1805

In your regular expression, you can use \b to detect beginning of new words and \w for "word characters":

"your string".replace(/\b\w+-line\b/g,'new_word')

See http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Upvotes: 0

fge
fge

Reputation: 121702

Try this as a regex:

/\S+-line(?![-\w])/

The word anchor is not suitable here since dashes are not considered part of a word, so /\S+-line\b/ would mistakenly match text-with-line-not-to-be-replaced. Hence the lookahead construct.

Of course, according to your use case, \S may seem a little coarse. If your words really only consist of letters then dashes etc, then you can use the normal* (special normal*)* pattern:

/[a-z]+(-[a-z]+)*-line(?![-\w])/i

(normal: [a-z], special: -)

(edit: changed the lookahead construct, thanks to @thg435)

Upvotes: 4

El Ronnoco
El Ronnoco

Reputation: 11922

How about

string.replace(/\b\S+-line\b/g,'new_word')

\b Word boundary

\S non whitespace

As fge astutely notes, we need a \b after line so we don't catch things ending lines liner etc etc etc

Upvotes: 0

Related Questions