Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match exact word not preceded or followed by other characters [duplicate]

im trying to make a regex for matching a set of words.

For example, if i am matching a set of words - American Tea

Then in the string American Tea is awesome. Do you like American Tea? love WowAmerican Tea #American Tea there will be only 2 matches here,

'American Tea is awesome. Do you like American Tea? love WowAmerican Tea #American Tea'

So, i am trying to do only full matches of the word set.

I tried some approaches, but havent got the correct regex :( If anyone can help or can point me in a direction it would be really helpful.

Check this

'American Tea lalalal qwqwqw American Tea sdsdsd #American Tea'.match(/(?:^|\s)(American Tea)(?=\s|$)/g)

the result of this is ["American Tea", " American Tea"]

I do not want the space in the second match, i want the match result to be ["American Tea", "American Tea"]

(no space in front of the second American Tea)

like image 295
ghostCoder Avatar asked Dec 31 '25 01:12

ghostCoder


1 Answers

Use .replace() for fun and profit

/(?:^|\s)(american tea)/ig

https://regex101.com/r/qB0uO2/1

if you want to account for prefixes AND suffixes:

/(?:^|\s)(american tea)(?:\W|$)/ig 

https://regex101.com/r/qB0uO2/2

JSBIN EXAMPLE

var str = "American Tea is awesome. Do you like American Tea? love WowAmerican Tea #American Tea";

str.replace(/(?:^|\s)(american tea)(?:\W|$)/ig, function(i, m){
  console.log(m);
});

//"American Tea"
//"American Tea"

EDIT:

The above returns only the matches, if instead you want to preserve the capturing and matching prefixes and suffixes use capturing-groups for them aswell:

var str = "American Tea is awesome. Do you like American Tea? love WowAmerican Tea #American Tea";

var newStr = str.replace(/(^|\s)(american tea)(\W|$)/ig, function(im, p1, p2, p3){
  return  p1 +"<b>"+ p2 +"</b>"+ p3; // p1 and p3 will help preserve the pref/suffix
});

document.getElementById("result").innerHTML = newStr;
<div id="result"></div>

where the parts

  • p1 is the first matching group (any prefix)
  • p2 is the second matching group (the "American Tea" word)
  • p3 is the third matching group (any suffix)
like image 69
Roko C. Buljan Avatar answered Jan 02 '26 15:01

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!