简体   繁体   中英

PCRE implementing negative lookahead AND behind working together?

Hi all,

I'm having a bit of a problem that I am obviously unable to solve. It involves PCRE implementing negative lookahead AND behind conditions that should (but obviuosly don't) work together.

What I'm trying to accomplish:

I have a string containing a constant in a JavaScript compliant syntax. This string's syntax needs to be converted to be adhering to JSON standards.

The problem I encounter:

When I try to encapsulate the object property keys with quotation marks, I need to distinct "real" property keys from strings contained in an array, that happen to look like property keys.

Example input (all JS):

const Const = {
  propertyKeyA: "someValue",
  propertyKeyB: ["ThisIsMyHeadache:ItShouldNotBeChanged"]
};

Desired output:

{
  "propertyKeyA": "someValue",
  "propertyKeyB": ["ThisIsMyHeadache:ItShouldNotBeChanged"]
}

My PCRE approach:

$output = preg_replace(
  '~(?:^|\b)    (?![\'"])  (\w+)  (?<![\'"])     :~mx',
  '"\1":',
  $input
);

which leads to:

{
  "propertyKeyA": "someValue",
  "propertyKeyB": [""ThisIsMyHeadache":ItShouldNotBeChanged"]
}

Notice the double quotation marks in the array definition. It seems to me as if the conditions do not work at all.

Does anyone have an idea on how to solve this? It would be immensely appreciated!

Best, Chris

You mixed lookahead and lookbehind positions.

The (?![\\'"])(\\w+) is equal to (\\w+) because (?![\\'"]) is a negative lookahead and requires the next char not to be a ' or " , but since the next pattern is \\w , matching a word char, the lookahead becomes redundant. You need to use a negative lookbehind here, (?<![\\'"]) (\\w+) . And the problem with (\\w+)(?<![\\'"]) is similar: the word char cannot be a ' and " and the negative lookbehind is redundant. You wanted a lookahead here.

You need to use

'~(?:^|\b) (?<![\'"]) (\w+) (?![\'"]) :~mx'

See the regex demo .

正如Wiktor在对我最初问题的评论中所发布的,这是解决方案:

'~(?:^|\b) (?<![\'"]) (\w+) (?![\'"]) :~mx'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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