【问题标题】:How to search for the second occurence of ' or " in regex?如何在正则表达式中搜索“或”的第二次出现?
【发布时间】:2013-08-16 14:42:32
【问题描述】:

字符串组合:

str_search = adfa odf 'aso'
str_search = do o sfo o'sfsdf'
str_search = sdfosd'sf sd'

到目前为止我做了什么:

if( /\s*\S*["|']\s*\S*["|']$/.test(str_search) ){
alert('at the 2nd quote');
    //replace the string enclosed in quotes with !string!
}//if

第一个块的字符串组合必须在第二个块的条件内。因此 ff 不应进入第二块中的条件

str_search = adfa odf 'aso
str_search = do o sfo osfsdf'
str_search = sdfosd'sf sd's

【问题讨论】:

  • "条件必须在...末尾为真" 恐怕我不知道您想告诉我们什么?你想用这些输入实现什么? = 的右侧是否实际上用引号括起来(即,"adfa odf 'aso'" 是字符串吗?)。
  • 您的正则表达式匹配至少有一个引号的字符串,但您的示例字符串只有撇号?
  • 你的意思是像this这样的东西吗?
  • @jerry - 是的,但我需要你需要包含 $,因为如果 str_search 的最后一部分是 ' 或 " 并且它看到的 ' 或 " 是第二次出现,它必须进入 cond

标签: javascript regex


【解决方案1】:

嗯,从你的更新来看,你似乎可以使用这样的东西:

str = "adfa odf 'aso'";

if(/(?:'[^']+'|"[^"]+")$/.test(str)){
    res = str.replace(/(?:'[^']+'|"[^"]+")$/, "!string!");
    alert(res);
}

JSFiddle.

【讨论】:

  • 如果 str = "adfa odf 'aso'a"; 则不能进入内部;
  • 我知道了,你的小提琴与这里发布的不匹配,非常感谢
【解决方案2】:

这样的东西可以用来替换引号中的字符串:

> "a 'asdf'".replace(/'[^']*'/, "replacement");
"a replacement"

用简单的英语:查找一个引号、任意数量的非引号字符和另一个引号,并将所有这些替换为“替换”。

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 2019-07-19
    • 2021-04-15
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多