简体   繁体   English

正则表达式在第n次出现字符时剪切字符串并返回字符串的第一部分

[英]Regex expression to cut string at nth occurrence of character and return first part of string

I have found the answer for a case which returns the second part of the string, eg: 我找到了一个返回字符串第二部分的案例的答案,例如:

"qwe_fs_xczv_xcv_xcv_x".replace(/([^\\_]*\\_){**nth**}/, ''); - where is nth is the amount of occurrence to remove. - nth是要删除的发生量。

If nth =3, the above will return “xcv_xcv_x” 如果nth = 3,以上将返回“xcv_xcv_x”

Details in this StackOverflow post: Cutting a string at nth occurrence of a character 此StackOverflow帖子中的详细信息: 在第n次出现字符时剪切字符串

How to change the above regular expression to return the first part instead (ie. “qwe_fs_xczv”)? 如何更改上面的正则表达式来返回第一部分(即“qwe_fs_xczv”)?

You need to use end anchor( $ ) to assert ending position. 您需要使用结束锚( $来断言结束位置。

"qwe_fs_xczv_xcv_xcv_x".replace(/(_[^_]*){nth}$/, ''); 
//            --------------------^-----------^--- here

 console.log( "qwe_fs_xczv_xcv_xcv_x".replace(/(_[^_]*){3}$/, '') ) 


UPDATE : In order to get the first n segments you need to use String#match method with slight variation in the regex. 更新:为了获得前n个段,您需要使用String#match方法,正则表达式略有变化。

"qwe_fs_xczv_xcv_xcv_x".match(/(?:(?:^|_)[^_]*){3}/)[0]

 console.log( "qwe_fs_xczv_xcv_xcv_x".match(/(?:(?:^|_)[^_]*){3}/)[0] ) 
In the above regex (?:^|_) helps to assert the start position or matching the leading _ . 在上面的正则表达式(?:^|_)有助于断言起始位置或匹配前导_ Regex explanation here . 正则表达式在这里解释


Another alternative for the regex would be, /^[^_]*(?:_[^_]*){n-1}/ . 正则表达式的另一种替代方案是/^[^_]*(?:_[^_]*){n-1}/ Final regex would be like: 最终的正则表达式将是:

 /^[^_]*(?:_[^_]*){2}/ 

 console.log( "qwe_fs_xczv_xcv_xcv_x".match(/^[^_]*(?:_[^_]*){2}/)[0] ) 

If you want to use replace , then capture up to right before the third _ and replace with that group: 如果要使用replace ,则在第三个_之前捕获,并替换为该组:

 const re = /^(([^_]*_){2}[^_]*(?=_)).*$/; console.log("qwe_fs_xczv_xcv_xcv_x".replace(re, '$1')); console.log("qwe_fs_xczv_xcv_xcv_x_x_x".replace(re, '$1')); 

But it would be nicer to use match to match the desired substring directly: 但是使用match直接匹配所需的子字符串会更好:

 const re = /^([^_]*_){2}[^_]*(?=_)/; console.log("qwe_fs_xczv_xcv_xcv_x".match(re)[0]) console.log("qwe_fs_xczv_xcv_xcv_x_x_x".match(re)[0]) 

Use String.match() to look from the start ( ^ ) of the string, for three sequences of characters without underscore, that might start with an underscore ( regex101 ): 使用String.match()从字符串的开头( ^ )查看三个没有下划线的字符序列,可以以下划线( regex101 )开头:

 const result = "qwe_fs_xczv_xcv_xcv_x".match(/^(?:_?[^_]+){3}/); console.log(result); 

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

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