Home > Software engineering >  RegEx for the string at the beginning of which there may be a version
RegEx for the string at the beginning of which there may be a version

Time:09-05

So, my program can accept strings like:

  • v00240004 Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  • v0345 Duis nec eleifend nulla..

and also a string without a version number:

  • Vivamus blandit et nibh nec placerat.
  • In hac habitasse platea dictumst. Suspendisse potenti.

I tried to write a regular expression to remove the version from the string. And it came out something like this: /^.*?\s/. It finds a match for the version and successfully replaces it with an empty string. But the problem is that it also works on strings without a version. That is, it removes the first word before the space.

So, my question is, how do I write a regular expression that works only on sentences starting with the letter "v" followed by numbers and replaces the version before the first space?

Example: A program receives 2 strings. The first v0255 Example1 string1 and the second Example2 string2. The result after the regular expression should be Example1 string1 and Example2 string2.

CodePudding user response:

This regex is going to help you match only those strings which have first word before space as 'v' then version number.

/^v\d.*?\s/gm

CodePudding user response:

Use the following regex:

^v.*?\s

See regex proof.

  • Related