简体   繁体   中英

regex pattern needed to replace

I am not too good at regular expressions so need some help from the community. any help is appreciated. I have a string as below

String str= "accountnumber,10000,accountname,Nachiket,balance,null,age,38"

I need a regex pattern to replace,10000, or,Nachiket, or,null, the string should look something similar

String str= "accountnumber,10000\naccountname,Nachiket\nbalance,null\nage,38"

This is my requirement. I have tried below pattern

String str=str.replace(",/[^a-z0-9-]/,",',/[^a-z0-9-]//n')

Thanks, Nachiket

It seems you are trying to group values like accountnumber,10000 and accountname,Nachiket etc. In that case, you can just search for two words and two comma patterns. Something like this:-

(.*?),(.*?),

Regex101 Sample - https://regex101.com/r/dEGs9c/1

And here is the JavaScript implementation

 let str = "accountnumber,10000,accountname,Nachiket,balance,null,age,38" let pattern = /(.*?),(.*?),/g let output = str.replace(pattern, (match)=> { // match will be => accountnumber,10000, => accountname,Nachiket, etc // use slice to remove the last character (comma) return match.slice(0, -1) + "\n" }) console.log(output)

Instead of using replace, you can match any char except a comma, followed by an optional part that matches a comma and again any char except a comma.

If you don't want to cross lines, you can use \n in the negated character class, or if you don't want to match spaces, you can use [^,\s]+

[^,\n]+(?:,[^,\n]+)?

Regex demo

 const regex = /[^,\n]+(?:,[^,\n]+)?/g; [ "accountnumber,10000,accountname,Nachiket,balance,null,age,38", "test1", "test2,test2", "test3,test3,test3" ].forEach(s => console.log(s.match(regex)));

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