开发者

Struggling with regex to match only two of a character, not three

I need to match all occurrences of // 开发者_高级运维in a string in a Javascript regex

It can't match /// or /

So far I have (.*[^\/])\/{2}([^\/].*)

which is basically "something that isn't /, followed by // followed by something that isn't /"

The approach seems to work apart from when the string I want to match starts with //

This doesn't work:

//example

This does

stuff // example

How do I solve this problem?

Edit: A bit more context - I am trying to replace // with !, so I am then using:

result = result.replace(myRegex, "$1 ! $2");


Replace two slashes that either begin the string or do not follow a slash, and are followed by anything not a slash or the end of the string.

s=s.replace(/(^|[^/])\/{2}([^/]|$)/g,'$1!$2');


It looks like it wouldn't work for example// either.

The problem is because you're matching // preceded and followed by at least one non-slash character. This can be solved by anchoring the regex, and then you can make the preceding/following text optional:

^(.*[^\/])?\/{2}([^\/].*)?$


Use negative lookahead/lookbehind assertions:

(.*)(?<!/)//(?!/)(.*)


Use this:

/([^/]*)(\/{2})([^/]*)/g

e.g.

alert("///exam//ple".replace(/([^/]*)(\/{2})([^/]*)/g, "$1$3"));  

EDIT: Updated the expression as per the comment.

/[/]{2}/

e.g:

alert("//example".replace(/[/]{2}/, ""));  


This does not answer the OP's question about using regex, but since some of the original comments suggested using .replaceAll, since not everyone who reads the question in the future wants to use regex, since people might mistakenly assume that regex is the only alternative, and since these details cannot be accommodated by submitting a comment, here's a poor man's non-regex approach:

  1. Temporarily replace the three contiguous characters with something that would never naturally occur — really important when dealing with user-entered values.
  2. Replace the remaining two contiguous characters using .replaceAll().
  3. Return the original three contiguous characters.

For instance, let's say you wanted to remove all instances of ".." without affecting occurrences of "...".

var cleansedText = $(this).text().toString()
    .replaceAll("...", "☰☸☧")
    .replaceAll("..", "")
    .replaceAll("☰☸☧", "...")
; 
$(this).text(cleansedText);

Perhaps not as fast as regex for longer strings, but works great for short ones.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜