This is a noob question
Suppose I search a string S
for a pattern P
. Now I would like to display a substring of the string, which surrounds P
. The substring should be only one line (ie N
characters) and contain whole words. How would you code it in JavaScript
?
For example:
Let S
= "Hello world, welcome to the universe", P
= "welcome", and N
= 15. The naive solution gives "ld, welcome to " (adding 4 chars before and after P
). I would like to "round" it up to "world, welcome to".
Can regular expressions help me here?
Here is the regular expression you wanted:
/\s?([^\s]+\swelcome\s[^\s]+)\s?/i //very simple, no a strange bunch of [] and {}
Explanation:
What you are trying to match is actually
" world, welcome to "
without the spaces before and after, therefore:
\s? //the first space (if found)
( //define the string position you want
[^\s]+ //any text (first word before "welcome", no space)
\s //a space
welcome //you word
\s //a space
[^\s]+ //the next world (no space inside)
) //that's it, I don't want the last space
\s? //the space at the end (if found)
Applying:
function find_it(p){
var s = "Hello world, welcome to the universe",
reg = new RegExp("\\s?([^\\s]+\\s" + p + "\\s[^\\s]+)\\s?", "i");
return s.match(reg) && s.match(reg)[1];
}
find_it("welcome"); //"world, welcome to"
find_it("world,"); //"Hello world, welcome"
find_it("universe"); //null (because there is no word after "universe")
I think, this is, what your are looking for.
$a = ($n - length of $p)/2
/[a-zA-Z0-9]{$a}$p[a-zA-Z0-9]{$a}/
I used dollars to show where the variables are. You didn't provide enough code to write a concrete example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.