如何使用正则表达式替换部分字符串?

时间:2018-04-08 15:56:21

标签: javascript regex replace

如何在Javascript中搜索[SM_g]randomword.[SM_h]的所有实例中的字符串,并将其全部替换为[SM_g]randomword[SM_h],

我也喜欢用逗号来做这件事。例如 - 我需要能够将[SM_g]randomword,[SM_h]转换为const periodRegex = /\[SM_g](.*?)\[SM_h](?:[.])/g; string_afterregex - string_initial.replace(periodRegex, /*I don't know what goes in here*/)

到目前为止,这是我的代码:

import React, { Component } from "react";
import {
  View,
  Text,
  Image,
  Animated,
  ScrollView,
  StyleSheet,
  Dimensions
} from "react-native";

import { PostProfileBar } from "../../component";

const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height / 3;

class SharePostScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      profile: {
        avatar:
          "https://img.bleacherreport.net/img/images/photos/003/733/498/hi-res-0579e42e6ee662e306e09bcf17d72dc4_crop_north.jpg?h=533&w=800&q=70&crop_x=center&crop_y=top",
        first_name: "Sarah",
        last_name: "Williams"
      }
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.sharePostWrapper}>
          <ScrollView>
            <PostProfileBar profile={this.state.profile} />
            <Image
              source={{
                uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
              }}
              resizeMode={'cover'}
              style={styles.image}
            />
          </ScrollView>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  sharePostWrapper: {
    flex: 1,
    margin: 5,
    padding: 5,
    borderWidth: 0.5,
    borderColor: 'gray',
  },
  image: {
    marginTop: 4,
    width: width - 20,
    height: height
  }
});

export default SharePostScreen;

2 个答案:

答案 0 :(得分:1)

捕获模式,然后使用后引用重新排序:

&#13;
&#13;
const periodRegex = /(\[SM_g].*?)(\[SM_h])([.,])/g;

var string_initial = '[SM_g]randomword[SM_h].'
var string_afterregex = string_initial.replace(periodRegex, "$1$3$2");
console.log(string_afterregex);

var string_initial = '[SM_g]randomword[SM_h],'
console.log(string_initial.replace(periodRegex, "$1$3$2"))
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您从前瞻中获益,则不必使用多个正则表达式来实现您的目标:

const re = /\[SM_g](?=(((?:(?!\[SM_h]).)*)\[SM_h])([.,]))\1./g;
const str = '[SM_g]$2$3[SM_h]';

console.log("[SM_g]WORD[SM_h], [SM_g]WORD[SM_h]. [SM_g]WORD[SM_h]".replace(re, str));

故障:

  • \[SM_g]按字面意思匹配[SM_g]
  • (?=开始积极前瞻
    • (开始捕获组#1
      • ( CG#2的开始
        • (?: NCG#1的开始,淬火点
          • (?!\[SM_h])。匹配下一个字符而不跳过[SM_h]
        • )* NCG#1结束,尽可能重复
      • ) CG#2结束
      • \[SM_h]按字面意思匹配[SM_h]
    • ) CG#2结束
    • ( CG#3的开始
      • [.,]匹配逗号或句点
    • ) CG#4结束
  • )结束了积极的向前看
  • \1.匹配CG#1匹配的字符