Home > Software design >  Regex : Keep only first term after the first hyphens
Regex : Keep only first term after the first hyphens

Time:12-12

I have thoses strings:

  • Connect-trzSimulation-dev-api
  • Nickazor-CoreConnect-dev-aggregationSync
  • Connect-TrzAuth-dev-api
  • Connect-CoreConnect-dev-api
  • Connect-trzSimulation-dev-api

And, i always need to keep the first term after the first hyphens, so:

  • trzSimulation
  • CoreConnect
  • TrzAuth

How can I do the regex that will allow me to do this please?

I'm so bad with regex ...

Thank's in advance.

CodePudding user response:

If you are using shell scripting:

Regex solution would be:

grep -(.*?)- filename

You could use "cut":

cut -d "-" -f2 filename

awk solution:

awk -F "-" '{print $2}' filename

where filename is the text file containing these strings mentioned by you

You could also use the said regex in python:

import re
x="Connect-trzSimulation-dev-api"
a=re.findall("\-(.*?)\-",x)
a

CodePudding user response:

You can use this site: https://regex101.com/ You can have a look here: https://regex101.com/r/Ca6NfH/1 the site explains everything as well, so it is pretty cool!

const str = 'Connect-trzSimulation-dev-api';

const result = str.match(/(?<=-)\w |\w (?=-)/gm);

console.log(result);

You can also simply use string.split('-') if you are using JS:

const str = 'Connect-trzSimulation-dev-api';

const result = str.split('-');

console.log(result);

  • Related