Home > Blockchain >  Creating a regular expression that replaces strings in quotes with empty strings
Creating a regular expression that replaces strings in quotes with empty strings

Time:07-18

How can I create a regular expression that finds the text wrapped in """ or ''' for example:

hello """
long text here,
e.g. a private SSH key
"""
this is a name for testing

'''
this is another multi-line 
stuff.
'''

I want to get the output like:

hello
this is a name for testing

With all the text that are in """ or ''' replaced with an empty string.

CodePudding user response:

Use """|''' as delimiters (with a \1 back-reference for the closing one), a non-greedy match-all (.*?) and the s (dot-all) and g (global) flags.

Remove leading and trailing white-space with trim().

const str = `hello """
long text here,
e.g. a private SSH key
"""
this is a name for testing

'''
this is another multi-line 
stuff.
'''`

console.log(str.replace(/("""|''').*?\1/gs, "").trim());

CodePudding user response:

We can try a regex replacement targeting all multiline quoted terms. We will use dot all mode to ensure that the matches occur across newlines.

var input = `
hello """
long text here,
e.g. a private SSH key
"""
this is a name for testing

'''
this is another multi-line 
stuff.
'''`;
var output = input.replace(/""".*?"""|'''.*?'''/sg, '').trim();
console.log(output);

  • Related