Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  187] [ 6]  / answers: 1 / hits: 20155  / 11 Years ago, sun, november 24, 2013, 12:00:00

This must be somewhere... but after wasting quite a bit of time, I can't find it:
I would like to test a string matching: in+ * +ing.




In other words,

interesting should result in true, whereas

insist and string should fail.




I am only interested in testing a single word, with no spaces.



I know I could do this in two tests, but I really want to do it one. As always, thanks for any help.


More From » regex

 Answers
26

If you specifically want to match words then try something like this:



/in[a-z]*ing/i


If you want in followed by any characters at all followed by ing then:



/in.*ing/i


The i after the second / makes it case insensitive. Either way replace the * with + if you want to have at least one character in between in and ing; * matches zero or more.



Given a variable in a string you could use the regex to test for a match like this:



var str = Interesting;
if (/in[a-z]*ing/i.test(str)) {
// we have a match
}


UPDATE




What if the prefix and suffix are stored in variables?




Well then instead of using a regex literal as shown above you'd use new RegExp() and pass a string representing the pattern.



var prefix = in,
suffix = ing,
re = new RegExp(prefix + [a-z]* + suffix, i);
if (re.match(Interesting)) {
// we have a match
}


All of the regular expressions I've shown so far will match the in something ing pattern anywhere within a larger string. If the idea is to test whether the entire string matches that mattern such that interesting would be a match but noninterestingstuff would not (as per stackunderflow's comment) then you need to match the start and end of the string with ^ and $:



/^in[a-z]*ing$/i


Or from variables:



new RegExp(^ + p + [a-z]* + s + $, i)


Or if you're testing the whole string you don't necessarily need regex (although I find regex simpler):



var str = Interesting,
prefix = in,
suffix = ing;
str = str.toLowerCase(); // if case is not important

if (str.indexOf(prefix)===0 && str.endsWith(suffix)){
// match do something
}


Or for browsers that don't support .endsWith():



if (str.slice(0,prefix.length)===prefix && str.slice(-suffix.length)===suffix)



What's the best I can read on the subject?




MDN gives a rundown of regex for JavaScript. regular-expressions.info gives a more general set of tutorials.


[#74101] Friday, November 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalaveronicab

Total Points: 3
Total Questions: 100
Total Answers: 105

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;