Babar
Babar

Reputation: 1202

Regular Expression word boundary breaks on '-'

I have a string in the following format.

"ad60 ad60-12 ad60 12-ad60"

now I want to find the matches only where "ad60" is written.

I started off with

/\bad60\b/i

but regex finds that '-' is not part of the character string. which returns 4 matches. I tried many things but they all either return 4 matches or return nothing.

Any kind of help would be appreciated.

Upvotes: 2

Views: 72

Answers (3)

Michael L.
Michael L.

Reputation: 379

"ad60 ad60-12 ad60 12-ad60".match(/(^ad60\s+)|(\s+ad60$)|(\s+ad60\s+)|(^ad60$)/ig);

will result in ["ad60 ", " ad60 "] then you can trim the white spaces in matched elements.

Upvotes: 0

anubhava
anubhava

Reputation: 785771

You can use:

var s = "ad60 ad60-12 ad60 12-ad60";
var r = s.replace(/(^|\s)ad60(?=\s|$)/g, "$1@@");
//=> @@ ad60-12 @@ 12-ad60

Upvotes: 2

Panoptik
Panoptik

Reputation: 1152

this should find any word starting from letter

/[a-z][a-z\d]+/i

ADDED

if you wish to find any words which are included ad60 string try this

/[a-z\d\-\_]*ad60[a-z\d\-\_]*/i

but words separated by space will not get in result

Upvotes: 0

Related Questions