简体   繁体   English

在第一次和第二次出现正斜杠之间替换字符串

[英]Replace string between first and second occurrence of forward slash

i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.我对正则表达式不是很熟悉,我需要帮助替换其中第一次和第二次出现正斜杠之间的字符串值。

Example例子

const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

Output: Output:

  1. /questions/ask/1 to /example/ask/1 /questions/ask/1/example/ask/1
  2. /questions-math/ask/1 to /example/ask/1 /questions-math/ask/1/example/ask/1

I can't seem to get right regex.我似乎无法获得正确的正则表达式。 Thanks for any help.谢谢你的帮助。 I know there are lot of similar questions but I just could not find a solution.我知道有很多类似的问题,但我找不到解决方案。

It may be better to use simple JS like this:使用这样的简单 JS 可能会更好:

var str = '/questions/ask/1';
var res = str.split("/");
res[1] = 'example';
res = res.join("/");

 var s = '/questions/ask/1'; var s2 = '/questions-math/ask/1'; var r = s.replace(/[^\/][-a-zA-Z]*/, 'example'); var r2 = s2.replace(/[^\/][-a-zA-Z]*/, 'example'); console.log(r); console.log(r2);

EDIT:编辑:

The issue of lazy vs greedy.懒惰与贪婪的问题。

For some incomprehensible reason, there is a fashion for using lazy-mode regular expressions.由于某些难以理解的原因,有一种使用惰性模式正则表达式的时尚。 Such expressions are not a panacea for everything.这样的表达方式并不是万能的。 In this case, the use of default greedy-mode expressions makes them easier to use and develop.在这种情况下,使用默认的贪婪模式表达式使它们更易于使用和开发。

"Higher performance" is also a myth, just think about the algorithm used but for illustration I compared these solutions by calculating the average of 100 tests each one million substitutions : “更高的性能”也是一个神话,想想所使用的算法,但为了说明,我通过计算每百万次替换的 100 次测试的平均值来比较这些解决方案:

I. 10-year PC, CPU 4 core 23145.70 BogoMIPS
Greedy:  278 ms
Lazy:    900 ms

II. 30-year PC, CPU 1 core 3397.11 BogoMIPS
Greedy:  6736 ms
Lazy:    7490 ms

As you can see, the unwavering expression turned out to be slower and this difference drastically increases with the increase in processor power.如您所见,坚定不移的表达式结果变得更慢,并且这种差异随着处理器能力的增加而急剧增加。

Note that these differences relate to 1 million substitutions, with one substitution they have absolutely no meaning.请注意,这些差异与 100 万次替换有关,其中一次替换完全没有意义。

Naturally, this will not be the case in all cases.当然,并非在所有情况下都是如此。 If we care about the performance of a function, there is no shortcut way, the answer will be given only by making measurements by profiling.如果我们关心一个function的性能,没有捷径可走,只有通过profiling测量才能给出答案。

If there has to be a second forward slash present in the string:如果字符串中必须第二个正斜杠:

^\/[^\/\r\n]+(?=\/)

Explanation解释

  • ^ Start of string ^字符串开头
  • \/ Match the first / \/匹配第一个/
  • [^\/\r\n]+ Match 1+ times any char except / or a newline [^\/\r\n]+匹配除/或换行符以外的任何字符 1+ 次
  • (?=\/) Positive lookahead, assert what is on the right is the second / (?=\/)正向前瞻,断言右边是第二个/

Regex demo正则表达式演示

In the replacement use the first / followed by example在替换中使用第一个/后跟example

 [ '/questions/ask/1', '/questions/', '/questions' ].forEach(s => console.log(s + " --> " + s.replace(/^\/[^\/\r\n]+(?=\/)/, "/example")) )

You can use the below regex:您可以使用以下正则表达式:

^(\/)(?:[-\w!#$]+)(.*?)$

Explanation of the regex:正则表达式的解释:

^ - Represents the start of the given string. ^ - 表示给定字符串的开始。

(\/) - Represents 1st capturing group. (\/) - 代表第一个捕获组。 This group is used in the replacement as $1 .该组在替换中用作$1

(?:[-\w!#$]+) - Represents a non-capturing group since you need to replace it containing word characters and all the special symbols that you need to replace one or more times . (?:[-\w!#$]+) - 表示非捕获组,因为您需要替换它,其中包含单词字符和所有需要替换一次或多次的特殊符号。 You can although add other special symbols that you need to exclude here.您可以在此处添加需要排除的其他特殊符号。

(.*?) - Represents 2nd capturing group capturing everything except the new line character lazily coming after your replacement. (.*?) - 表示第二个捕获组捕获除了新行字符之外的所有内容,在替换后懒惰地出现。 This group is used in the replacement as $2 .该组在替换中用作$2

$ - Represents the end of the given test String. $ - 表示给定测试字符串的结尾。

You can find the demo of the above regex in here.您可以在此处找到上述正则表达式的演示。

IMPLEMENTATION IN JAVASCRIPT: JAVASCRIPT 中的实现:

 const regex = /^(\/)(?:[-\w.#$]+)(?*;)$/gm; const str = `/questions-math/ask/1 /questions/ask/1`; const subst = `$1examples$2`. // The substituted value will be contained in the result variable const result = str,replace(regex; subst). console;log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM