[英]Finding the first occurrence of a given/ specific character inside every word
stringi = "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
I was able to make a regEx to DYNAMICALLY find every last occurrence of a character X in every word: (I call it dynamically because I only have to change ONE spot) 我能够使regEx动态地找到每个单词中字符X的最后一次出现:(我动态地调用它,因为我只需要更改一个点即可)
(n)(?!(\\w+?)?\\1(\\w+?)?)
gives (n)(?!(\\w+?)?\\1(\\w+?)?)
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
(d)(?!(\\w+?)?\\1(\\w+?)?)
gives (d)(?!(\\w+?)?\\1(\\w+?)?)
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
How can I get a "dynamic" regEx. 如何获得“动态” regEx。 That means I have to replace one spot like above to give me:
这意味着我必须替换上面的一个位置才能给我:
some regEx with >>> n <<<
gives some regEx with >>> n <<<
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
some regEx with >>> d <<<
gives some regEx with >>> d <<<
给出
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
Is it possible to match those with a regEx and that I only have to change ONE spot when I want to match another character? 是否可以将它们与regEx匹配,并且在我要匹配另一个字符时只需要更改一个位置?
Pure regEx, no js string splitting etc.. 纯正则表达式,无js字符串拆分等。
With the lookbehind I run into a fixed length problem. 有了后顾之忧,我遇到了固定长度的问题。
That means I have to replace one spot
这意味着我必须替换一个位置
You first match n
then every thing else: 您首先匹配
n
然后匹配其他所有内容:
n(\S*)
var str = "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"; var char = 'n'; console.log(str.replace(new RegExp(char + '(\\\\S*)', 'g'), '*$1')); var char = 'd'; console.log(str.replace(new RegExp(char + '(\\\\S*)', 'g'), '*$1'));
If it's a matter of interest, since Chrome has implemented lookbehinds (that luckily are infnite lookbehinds) you can acheive same result with this regex: 如果有兴趣的话,由于Chrome已经实现了 lookbehinds(幸运的是,是infnite lookbehinds),因此您可以使用此正则表达式达到相同的结果:
(?<!n\S*)n
In this regex demo , the lookbehind seems to be okay with not fixed length - with javascript. 在此regex演示中 ,使用固定长度的固定长度(不是固定长度)的方法看起来不错。 So this is the regex:
所以这是正则表达式:
(?<=\b[^\Wd]*)d
Explanation: 说明:
\\b
is a word barrier \\b
是一个单词障碍 [^d]*d
finds non- d
characters, and then a d
[^d]*d
查找非d
字符,然后查找d
[^\\Wd]
is not a d
but word characters. [^\\Wd]
不是d
而是单词字符。 Ie \\W
is not a word character, so [^\\W]
is a word character. \\W
不是文字字符,因此[^\\W]
是文字字符。 So [^\\Wd]
is every word character, except d
[^\\Wd]
是除d
以外的每个单词字符 \\b[^\\Wd]*d
would match the start of every word, up to the first d
. \\b[^\\Wd]*d
将匹配每个单词的开头,直到第一个d
为止。 Using the right constructs, this could be enough. (?<=...)
is the lookbehind. (?<=...)
是后面的样子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.