简体   繁体   中英

Regular expression replace only one matching

I have a regular expression code in JavaScript

const regexns = /[A-Za-z]\:[A-Za-z]/gi;
data = data.replace(regexns, '__NS__');

If I apply on this XML

<AnchorPane prefHeight="400.0" prefWidth="600.0"
    xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="com.zigma.Controller">

I get

<AnchorPane prefHeight="400.0" prefWidth="600.0"
    xmlns="http://javafx.com/javafx/8" xmln__NS__x="http://javafx.com/fxml/1"
    f__NS__ontroller="com.zigma.Controller">

which means I loose 1 letter next and previous to :

How to replace the : without loosing those side letters,
is there any option in regular expression itself or we need to do loops and conditions and split like that?

Expected output is

<AnchorPane prefHeight="400.0" prefWidth="600.0"
    xmlns="http://javafx.com/javafx/8" xmlns__NS__fx="http://javafx.com/fxml/1"
    fx__NS__controller="com.zigma.Controller">

Capture the letter before the : so it can be added into the replacement, and lookahead for the letter after the : so it doesn't get matched. Also note that since you're using the case-insensitive flag, there's no need to repeat [A-Za-z] , and colons do not need to be escaped:

 const data = `<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.zigma.Controller"> `; console.log(data.replace(/([az]):(?=[az])/gi, '$1__NS__'));

Depending on the shape of your input, you may be able to use word boundaries instead:

 const data = `<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.zigma.Controller"> `; console.log(data.replace(/\\b:\\b/gi, '__NS__'));

For something even more robust I'd recommend parsing the string into an XML document, and then iterating through the elements of the document, replacing attributes which contain the : pattern with the new attribute.

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