473,884 Members | 2,403 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regex, what is wrong

Hello, what is wrong with this code, I want to divide string to pieces 4
chars length.

string tekst = "divide string to 4 chars pieces";
Regex regex = new Regex("(.{1,4}) ");
string[] substrings = regex.Split(tek st);

but instead of array with:
"divi","de s","trin" etc..
i have
"","divi","","d e s","","trin" , etc..

What is wrong?
Sep 8 '08 #1
8 1350
ad******@antysp am.pl wrote:
Hello, what is wrong with this code, I want to divide string to pieces 4
chars length.

string tekst = "divide string to 4 chars pieces";
Regex regex = new Regex("(.{1,4}) ");
string[] substrings = regex.Split(tek st);

but instead of array with:
"divi","de s","trin" etc..
i have
"","divi","","d e s","","trin" , etc..

What is wrong?
There is nothing wrong. You are splitting the string with four
characters as separator. That means that the first separator is found at
the first character, the second separator is found at the fifth
character, and so on. All you find in the string is separators, and no
text between them.

The result is the text separated by the separators, and the separators
between them. As the separator matches anything, the strings separated
by the separators all become empty strings.

It's similar to doing this:

",,,".Split(',' )

the result would be an array with four empty strings, as the string only
consists of separators.

--
Göran Andersson
_____
http://www.guffa.com
Sep 8 '08 #2
Göran Andersson pisze:
There is nothing wrong. You are splitting the string with four
characters as separator. That means that the first separator is found at
[cut]
the result would be an array with four empty strings, as the string only
consists of separators.
Thanks.

So, is there any way to split string into numbered pieces by using Regex
, instead of using Substring etc...? There is no String.Split(In t) in
framework
Sep 8 '08 #3
Why not just use Substring? For example (in this case using C# 3.0
extension methods, but would work just as well without them...):

Marc

using System;
using System.Collecti ons.Generic;
using System.Linq;
static class Program
{
static void Main()
{

string test = "divide string to 4 chars pieces";
foreach (string s in test.Split(4))
{
Console.WriteLi ne(s);
}
// or alternatively.. .
string[] split = test.Split(4).T oArray();
}
public static IEnumerable<str ingSplit(this string value, int size)
{
int offset = 0, remaining = value.Length;
while (remaining >= size)
{
yield return value.Substring (offset, size);
offset += size;
remaining -= size;
}
if (remaining 0) yield return value.Substring (offset);
}
}
Sep 8 '08 #4
you might want to add:

if (value == null) throw new ArgumentNullExc eption("value") ;
if (size <= 0) throw new ArgumentOutOfRa ngeException("s ize",
"Size must be positive");
Sep 8 '08 #5
Marc Gravell pisze:
Why not just use Substring?
Because i don't want :) , i'm curious how to do it with Regex.
Sep 8 '08 #6
Hi Mark.

Not to want to be picky or anything but to make this code more robust
I think you will also need to account for Unicode strings that are not
normalized.

For example, things like combining marks such as Unicode code point U
+00E0 (http://www.fileformat.info/info/unic...00e0/index.htm)
that can also be represented as U+0061 U+0300.

Simply splitting the string may yield unexpected results.

I have no doubt that you already knew this and that the sample you
posted is just to illustrate your point but I thought I would just
point the issue out so that the original poster is aware of it (in
case he/she is not already).

Of course, I may be totally wrong about what I my comment so if that
is the case just ignore me!!!!

Cheers.


On Sep 8, 5:05*am, Marc Gravell <marc.grav...@g mail.comwrote:
Why not just use Substring? For example (in this case using C# 3.0
extension methods, but would work just as well without them...):

Marc

using System;
using System.Collecti ons.Generic;
using System.Linq;
static class Program
{
* * *static void Main()
* * *{

* * * * *string test = "divide string to 4 chars pieces";
* * * * *foreach (string s in test.Split(4))
* * * * *{
* * * * * * *Console.WriteL ine(s);
* * * * *}
* * * * *// or alternatively.. .
* * * * *string[] split = test.Split(4).T oArray();
* * *}
* * *public static IEnumerable<str ingSplit(this string value, intsize)
* * *{
* * * * *int offset = 0, remaining = value.Length;
* * * * *while (remaining >= size)
* * * * *{
* * * * * * *yield return value.Substring (offset, size);
* * * * * * *offset += size;
* * * * * * *remaining -= size;
* * * * *}
* * * * *if (remaining 0) yield return value.Substring (offset);
* * *}

}- Hide quoted text -

- Show quoted text -
Sep 8 '08 #7
ad******@antysp am.pl wrote:
Marc Gravell pisze:
>Why not just use Substring?

Because i don't want :) , i'm curious how to do it with Regex.
Then use Match instead of Split.
Sep 8 '08 #8
but to make this code more robust
I think you will also need to account for Unicode strings that are not
normalized.
A fair point - but this same problem will affect most simple
mechanisms to split the string (including the original regex, it would
seem).

Marc
Sep 9 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
9783
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a numeric value according to an arbitrary regular expression.
7
2625
by: bill tie | last post by:
I'd appreciate it if you could advise. 1. How do I replace "\" (backslash) with anything? 2. Suppose I want to replace (a) every occurrence of characters "a", "b", "c", "d" with "x", (b) every occurrence of characters "p", "q", "r", "s" with "y". Right now, I do it as follows:
3
1490
by: dje | last post by:
Regex regex = new Regex("//"); Match match; match = regex.Match(this.LastName.Text); if(!match.Success) { sb.Append("Last name invalid. "); returnValue=false; } with the input "jones", match.Success always fails. Is there something wrong with my regular expression or am I not using Regex correctly?
2
1219
by: George Durzi | last post by:
Consider the following HTML snippet. I want to extract the section shown below. <!-- some html --> <TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=0 border=0><?xml version=1.0 encoding=UTF-16?> ** There is some HTML here that I want to extract ** </TABLE> <!-- some html -->
6
1784
by: tshad | last post by:
Is there a way to use Regex inside of a tag, such as asp:label? I tried something like this but can't make it work: <asp:label id="Phone" text=Regex.Replace('<%# Container.DataItem("Phone") %>',"(\d{3})(\d{3})(\d{4})","($1) $2-$3") runat="server"/> I have this inside my Repeater and want it to filter the field during bind. I can do it afterwards by just looping through the repeater items, but that is extra work and time.
7
2235
by: Mike Labosh | last post by:
I have the following System.Text.RegularExpressions.Regex that is supposed to remove this predefined list of garbage characters from contact names that come in on import files : Dim _dropContactGarbage As New Regex( _ "(+)|" & _ "(+)|" & _ "(+)|" & _ "(+)|" & _ "(+)|" & _
4
2651
by: Chris | last post by:
Hi Everyone, I am using a regex to check for a string. When all the file contains is my test string the regex returns a match, but when I embed the test string in the middle of a text file a match is never returned. The string that I give to the regex is one that contains the entire contents of a text file. I'm using the multi-line option and I've also tried stripping out the VbCr
6
9673
by: Gary Bond | last post by:
Hi All, Being a bit of a newbie with regex, I am confused when using word boundaries. For instance, I want to replace all the stand alone '.5k' that occur in an input string, with 500. In other words "this is a .5k example" goes to "this is a 500 example" The replace should not touch '.5k' that occurs inside a word. For example:
10
1893
by: bullockbefriending bard | last post by:
first, regex part: I am new to regexes and have come up with the following expression: ((1|),(1|)/){5}(1|),(1|) to exactly match strings which look like this: 1,2/3,4/5,6/7,8/9,10/11,12 i.e. 6 comma-delimited pairs of integer numbers separated by the
0
9954
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10869
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10426
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7985
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7137
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4623
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4231
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3243
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.