简体   繁体   中英

Regex match text between groups match

I'm doing a regex to separate as a key: value the text entry is similar to this

QA~BlaBlaBlaWE~1235123FA~blablablaER~blabla123ZX~2342blaaa

I have been able to separate it but when trying to take Group3 as a key and Group4 as a value

the QA ~ BlaBlaBla

it remains in Group2 (QA) and Group3 the value (BlaBlaBla)

my regex is this

((\\w{2}~)?(.*?)(\\w{2}~|$))

the point is to be able to create a list like this

> Key Value 
> QA BlaBlaBla 
> WE 1235123 
> FA blablabla 
> ER blabla123 
> ZX 2342blaaa

and here is the example https://regex101.com/r/Xh8RAA/1

I can not create the regex well so that everything is in Group3 and Group4 someone can help me

What you're looking for is lookahead , which will check that the current position is followed by some pattern without consuming characters in the pattern. You can also remove the unnecessary capturing group enclosing the whole regex, so you can get group 1 to contain the key, and group 2 to contain the value, without any other groups. Also, because the keys are required, the key group shouldn't be optional:

(\w{2})~(.*?)(?=\w{2}~|$)

https://regex101.com/r/Xh8RAA/6

You can use a positive lookahead pattern to avoid consuming the next header token:

([A-Z]{2})~(.*?)(?=[A-Z]{2}~|$)

Substitute the match with group 1 and group 2 followed by a newline and you will get the desired output.

Demo: https://regex101.com/r/Xh8RAA/2

You can try this Regular Expression :

/.{2}~[^~]+((?=..~)|$)/g

check its result below:

 console.log("QA~BlaBlaBlaWE~1235123FA~blablablaER~blabla123ZX~2342blaaa".match(/.{2}~[^~]+((?=..~)|$)/g));

With the code below you can get it as object ( key/val ):

 function CustomSplit(s){ var r={}; s.match(/(.{2})~([^~]+((?=..~)|$))/g).forEach(function(a){a=a.split("~"); r[a[0]]=a[1];}); return r; } console.log(CustomSplit("QA~BlaBlaBlaWE~1235123FA~blablablaER~blabla123ZX~2342blaaa"));

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