Coder
Coder

Reputation: 610

Regex for certain character and anything after that

I need to call minus/hyphen (-) as minus when it comes between one number or any other character. otherwise, if it comes between characters I need to replace it with an empty string.

For replacing '-' to empty string

readOutText = 'akhila-hegde'
readOutText = readOutText.replace(/([A-Za-z])-([A-Za-z]){0}\w/gi, ' '); // replace '-' with ' '

Now replace '-' with 'minus' in all of the scenarios

9 - {{response}}
9-{{response}}
{{response}}-9
{{response}} - 9
7346788-literallyanything
literallyanything-347583475

I am trying expression in this in this site https://regexr.com/

I have tried a couple of RegEX for 9-{{response}} tyeps.

readOutText = readOutText.replace(/([0-9])[ ]{0,1}-[ ]*\w/gi, ' minus '); // Not working 
readOutText = readOutText.replace(/([0-9])[ ]{0,1}-([a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/? ])\w/gi, ' minus ')

Both of these are matching with 9-{ in the string 9-{{response}}

If I know the above type I can do the same for {{response}}-473 type

Can someone help me with what I have missed?

Upvotes: 0

Views: 59

Answers (2)

The Fool
The Fool

Reputation: 20467

I made a small example using capture groups to capture the hyphen and classify as minus or true hpyhen. https://regex101.com/r/zb2eZv/1

Capture Group 1 is minus and capture group 2 is hyphen.

(?:\d+(-)\d+)|(?:\w+(-)\w+)

regex visualization

https://jex.im/regulex/#!flags=&re=(%3F%3A%5Cd%2B(-)%5Cd%2B)%7C(%3F%3A%5Cw%2B(-)%5Cw%2B)

Upvotes: 2

Jeremy Thille
Jeremy Thille

Reputation: 26370

It's a litte resource-intensive, and there might be cleverer solutions, but I believe you need a multipass replace.

  • Replace in case of digit dash digit
  • Replace in case of digit dash not-digit
  • Replace in case of not-digit dash digit

This will ignore all non-digit dash non-digit cases.

By the way, [0-9] can be replaced with \d (digit) and [ ]{0,1} can be replaced with * (zero or more spaces).

const inputs = [
    "akhila-hegde",
    "6 -4",
    "9 - {{response}}",
    "9-{{response}}",
    "{{response}}-9",
    "{{response}} - 9",
    "7346788-literallyanything",
    "literallyanything-347583475",
    "7- 8 and some-composed - word then 4-9"
];

const transformMinus = word => word
                .replace(/(\d) *- *(\d)/g, "$1 minus $2")
                .replace(/(\d) *- *(\D)/g, "$1 minus $2")
                .replace(/(\D) *- *(\d)/g, "$1 minus $2")


const outputs = inputs.map(transformMinus);

console.log(outputs);

Upvotes: 1

Related Questions