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

twitter logo github logo ・1 min read

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 = "The Initial Macports"
d = "The Oscar Macports Initial Time"
e = "macports"
f = "The fastest macport"

All the above are strings where the common word is macport. Just like these 6 strings I am operating on a data of almost 1000 variation like this.

I am trying out to find the strings which contains the name macport or macports.

Glad if you could give me suggestions or discuss about it, how to fix it

twitter logo DISCUSS (11)
markdown guide
 

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.

 

/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

 

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

 

No, i want to include macport and macports both.

 

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

 

in ruby if checking per string

 "The fastest macport".include?('macport')
 

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

 
 

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.

Classic DEV Post from May 19

Solving Puzzles With High-Performance JavaScript

Ali Rizvi profile image
MERN Stack Developer, with the passion to develop apps that can make this world better. "Whenever I get bored, I call API's"