nachiket26
nachiket26

Reputation: 19

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

Upvotes: 0

Views: 46

Answers (2)

The fourth bird
The fourth bird

Reputation: 163467

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)));

Upvotes: 0

Iftieaq
Iftieaq

Reputation: 1964

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)

Upvotes: 1

Related Questions