简体   繁体   中英

Is it possible to match half of a string using regex or use half of a matched group?

I have a string of the following form "some_text_AAAABB_some_other_text". There is an arbitrary even number of 'A's in the string and "BB" is a fixed string that follows the 'A's. Assuming that there is 2n 'A's I would like to use a regex to replace the 'A's with a string of 'A's of length n .

For the following string

"some_text_AAAABB_some_other_text"

the result would be

"some_text_AABB_some_other_text"

Is it even possible to achieve this with regex?

I'm using V8 javascript to perform the transformation.

There are two scenarios: 1) number of A s is even, 2) number of A s is odd.

If you do not care if there is an even or odd number of A s, just use

replace(/(A+)\1BB/g, "$1BB")

where (A+) matches and captures into Group 1 one or more A s as many as possible and \\1 matches the same substring (the same number as is captured into Group 1). Since BB is a fixed string, we just put it into the pattern as a literal.

See this regex demo

If you do not want to modify a string with odd number of A s, you need

replace(/(^|[^A-Z])(A+)\2BB/g, "$1$2BB")

See this regex demo

Here, the first capture group captures the start of string ^ or any character other than [AZ] , the second capture group captures 1 or more A s, and the backreference now has the ID = 2 - hence, \\2 is used.

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