简体   繁体   English

在javascript中使用正则表达式提取字符串

[英]Extraction of string using regex in javascript

I have a string of the following format: 我有以下格式的字符串:

"hello(%npm%)hi"

My goal is to split the string into three parts 我的目标是将字符串分成三部分

a) hello
b) (%npm%)
c) hi

I am using regex as follows: 我使用正则表达式如下:

var myString = "hello(%npm%)hi".match(/[a-z]*/);
        var backdtring  = "hello(%npm%)hi".match(/\)[a-z]*/);
        var midstring  = "hello(%npm%)hi".match(/\(\%[a-z]*\%\)/);

var res = backdtring.replace(")", "");

https://jsfiddle.net/1988/ff6aupmL/ https://jsfiddle.net/1988/ff6aupmL/

I am trying in jsfiddle , where theres an error in the line: 我正在jsfiddle中尝试,其中该行存在错误:

var res = backdtring.replace(")", "");

"backdtring.replace is not a function" . “ backdtring.replace不是函数”

Whats wrong in the replace function above? 上面的替换功能有什么问题?

Update: Also, have I used the best practices of regular expressions ? 更新:另外,我是否使用了正则表达式的最佳实践?

As it has been mentioned in the comments, you are trying to use a String#replace method on an array, see the description of the return value of String#match : 正如评论中提到的那样,您试图在数组上使用String#replace方法,请参见String#match返回值的描述:

An Array containing the entire match result and any parentheses-captured matched results; 一个包含整个匹配结果和任何用括号捕获的匹配结果的数组 null if there were no matches. 如果没有匹配项,则为null

To streamline tokenization, I'd rather use .split(/(\\([^()]*\\))/) to get all substrings in parentheses and the substrings that remain: 为了简化标记化,我宁愿使用.split(/(\\([^()]*\\))/)来获取括号中的所有子字符串,并保留剩余的子字符串:

 var s = "hello(%npm%)hi"; var res = s.split(/(\\([^()]*\\))/); console.log(res); 

Details : 详细资料

  • (\\([^()]*\\)) - the pattern is enclosed with capturing group so as split could return both the substrings that match and those that do not match the pattern (\\([^()]*\\)) -模式包含在捕获组中,以便split可以返回匹配模式的子字符串和不匹配模式的子字符串
  • \\( -a literal ( \\( -文字(
  • [^()]* - 0+ chars other than ( and ) [^()]* - ()以外的0+个字符
  • \\) - a literal ) . \\) -文字)

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

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