remove leading zeros in middle of string with regex

  • Last Update :
  • Techknowledgy :

Given numeric string str, the task is to remove all the leading zeros from a given string. If the string contains only zeros, then print a single “0”.,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,Create a Regular Expression as given below to remove the leading zeros,To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter.

1023
123

1234

Suggestion : 2

Your strings are fixed-length. Just cut them at the appropriate positions.

s = "112233440012345655667788"
int(s[8: 16])
# - > 123456

I think it's simpler not to use regex.

result = my_str[8: 16].lstrip('0')
# CODE AUTO GENERATED BY REGEX101.COM(SEE LINK ABOVE)
# coding = utf8
# the above tag defines encoding
for this document and is
for Python 2. x compatibility

import re

regex = r "(?<=\d{8})((?:0*)(\d{,8}))(?=\d{8})"

test_str = ("112233441234567855667788\n"
   "112233440012345655667788\n"
   "112233001234567855667788\n"
   "112233000012345655667788")

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
   matchNum = matchNum + 1

print("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

for groupNum in range(0, len(match.groups())):
   groupNum = groupNum + 1

print("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur ""
to prefix the regex and u ""
to prefix the test string and substitution.

Suggestion : 3

In this post find out about how to trim and remove leading zeros in JavaScript using parseInt, the addition operator and regex,This post assumes that your number is in the form of a string and we will look into how to trim and remove leading zeros from a string in JavaScript.,The best option to be able to trim or remove leading zeros in JavaScript is the parseInt method whilst proving the correct radix like in the example above.,There we have how to trim and remove leading zeros in JavaScript, if you want more like this be sure to check out some of my other posts!

parseInt("0400", 10) // 400
+"0400" // 400
"0400".replace(/^0+/, "") // "400"

Suggestion : 4

The Trim(System.Char[]) method removes from the current string all leading and trailing characters that are in the trimChars parameter. Each leading and trailing trim operation stops when a character that is not in trimChars is encountered. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the Trim(System.Char[]) method returns "abc456xyz".,The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz". To remove white-space characters between words in a string, use .NET Regular Expressions.,Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.,If trimChars is null or an empty array, this method removes any leading or trailing characters that result in the method returning true when they are passed to the Char.IsWhiteSpace method.

1._
public:
System::String ^ Trim(... cli::array <char> ^ trimChars);
public:
 System::String ^ Trim(... cli::array <char> ^ trimChars);
public string Trim(params char[] trimChars);
public string Trim (params char[] trimChars);
public string Trim(params char[] ? trimChars);
member this.Trim : char[] -> string
Public Function Trim(ParamArray trimChars As Char()) As String

The following example uses the Trim(System.Char[]) method to remove space, asterisk (*), and apostrophe (') characters from a string.

using namespace System;

void main()
{
   array<Char>^ charsToTrim = { L'*', L' ', L'\\' };
   String^ banner = "*** Much Ado About Nothing ***";
   String^ result = banner->Trim(charsToTrim);
   Console::WriteLine("Trimmmed\n   {0}\nto\n   '{1}'", banner, result);
}
// The example displays the following output:
//       Trimmmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'
1._
public:
   System::String ^ Trim(char trimChar);
public:
 System::String ^ Trim(char trimChar);
public string Trim(char trimChar);
public string Trim (char trimChar);
member this.Trim: char - > string
1._
public:
   System::String ^ Trim();
public:
 System::String ^ Trim();
public string Trim();
public string Trim ();
member this.Trim: unit - > string

The following example uses the String.Trim() method to remove any extra white space from strings entered by the user before concatenating them.

using namespace System;

void main() {
   Console::Write("Enter your first name: ");
   String ^ firstName = Console::ReadLine();

   Console::Write("Enter your middle name or initial: ");
   String ^ middleName = Console::ReadLine();

   Console::Write("Enter your last name: ");
   String ^ lastName = Console::ReadLine();

   Console::WriteLine();
   Console::WriteLine("You entered '{0}', '{1}', and '{2}'.",
      firstName, middleName, lastName);

   String ^ name = ((firstName - > Trim() + " " + middleName - > Trim()) - > Trim() + " " +
      lastName - > Trim()) - > Trim();
   Console::WriteLine("The result is " + name + ".");
}
// The following is possible output from this example:
//       Enter your first name:    John
//       Enter your middle name or initial:
//       Enter your last name:    Doe
//       
//       You entered '   John  ', '', and '   Doe'.
//       The result is John Doe.
using System;

public class Example {
   public static void Main() {
      Console.Write("Enter your first name: ");
      string firstName = Console.ReadLine();

      Console.Write("Enter your middle name or initial: ");
      string middleName = Console.ReadLine();

      Console.Write("Enter your last name: ");
      string lastName = Console.ReadLine();

      Console.WriteLine();
      Console.WriteLine("You entered '{0}', '{1}', and '{2}'.",
         firstName, middleName, lastName);

      string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " +
         lastName.Trim()).Trim();
      Console.WriteLine("The result is " + name + ".");

      // The following is a possible output from this example:
      //       Enter your first name:    John
      //       Enter your middle name or initial:
      //       Enter your last name:    Doe
      //       
      //       You entered '   John  ', '', and '   Doe'.
      //       The result is John Doe.
   }
}