简体   繁体   English

如何匹配字符开头没有的字符串?

[英]How do I match a string that is not preceeded by a character?

I have an array of strings and I need to perform a search and replace on them using JavaScript. 我有一个字符串数组,我需要执行搜索并使用JavaScript替换它们。 The issue is they only need to be found when they are not preceeded by one of two characters. 问题在于,仅当两个字符中的一个没有出现时才需要找到它们。 What I have tried is: 我试过的是:

 var searchString = new RegExp( "(?<![#\|])" + tableName,"");
 if(theLine.search(searchString) != -1){do something;}

tableName is variable and changes for each call based on data retreived from a database. tableName是可变的,并且每次调用都会根据从数据库检索到的数据进行更改。

If tableName is Fred, I want to find Fred but not #Fred or |Fred. 如果tableName为Fred,我想查找Fred,但不查找#Fred或| Fred。

What I have doesn't work and I'm not sure why. 我拥有的东西行不通,我不确定为什么。 It's probably a simple goof but I don't see it. 这可能是一个简单的蠢事,但我看不到。

JavaScript regex engine doesn't support lookbehinds . JavaScript正则表达式引擎不支持lookbehinds But you can do something like this regex to overcome that issue: 但是您可以执行以下正则表达式来解决该问题:

var s = 'If tableName is Fred, I want to find Fred but not #Fred or |Fred';
var r = s.replace(/([#|]Fred)|Fred/g, '$1')
//=> If tableName is , I want to find  but not #Fred or |Fred
var s = 'If tableName is Fred, I want to find Fred but not #Fred or |Fred';
s.match(/[^#\|]Fred/g)
[" Fred", " Fred"]

Though my answer contains an Extra Space. 虽然我的答案包含一个额外的空间。 You need to do is 你需要做的是

var s = 'If tableName is Fred, I want to find TFred Fred but not #Fred or |Fred';

var replaceWith = "XXXX";
s.replace(/[^#\|]Fred/g, function($1) {
    if($1 != $1.trim()) {
        return " " + replaceWith;
    } else {
        return replaceWith;
    }
})

//output - "If tableName is XXXX, I want to find XXXX XXXX but not #Fred or |Fred"
var searchString = new RegExp("(?<![^\|\#])" + tableName,"");
if (theLine.search(searchString) != -1){do something;}

You forgot to negate the character range that you don't want it to match on. 您忘了否定不希望与之匹配的字符范围。

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

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