DEV Community

How to find a string, within a string, using Regex

Ali Abbas on October 22, 2019

Thanks for stopping by. I am stuck in a problem that I'm unable to solve. The problem is like as follows a = "The Macports" b = "macport" c = "Th...
Collapse
 
savagepixie profile image
SavagePixie

Do you have them in an array? That'd be ideal, as you could do something like this:

const getWords = arr => {
   const regEx = /macports?/i
   return arr.filter(x => regEx.test(x))
}

If no array, then forget about the filter, but you can still apply the same principle.

Another way to go would be:

string.includes("macport")

Though you might have to turn the string into lower case for this one.

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

/macport$|macport /g.test(string)

This will check for words having macport and a space appeneded or a string that ends with macport

for macports you can do the same thing by replacing macport with macports

I am on mobile so didn't check it much just check if it is working and I may have missed some cases

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Oh I replied with the sense that you want to differentiate between macport and macports, is this what you want?

Collapse
 
realabbas profile image
Ali Abbas

No, i want to include macport and macports both.

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

oh then string.includes('macport') would work

Collapse
 
savagepixie profile image
SavagePixie

Oh, that's a very good point. It does change the answer.

Collapse
 
webcoderph profile image
Maynard Cabalitan

in ruby if checking per string

 "The fastest macport".include?('macport')
Collapse
 
devdrake0 profile image
Si

Can you update the title of your post to better indicate what your issue is, so people searching may find the issue easier?

Collapse
 
realabbas profile image
Ali Abbas

Okay Sure

Collapse
 
devdrake0 profile image
Si

I was thinking something more like:

How to find a string, within a string, using Regex

or something that actually summarises the issue you're wanting help for. "Can you help me" doesn't really give an initial indication of what's being asked.

Thread Thread
 
realabbas profile image
Ali Abbas

Okay! Done