473,938 Members | 5,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

regex split

Would like help with a (I think) a common regex split example. Thanks for
your example in advance. Cheers!

Source Data Example:
one "two three" four

Optional, but would also like to ignore pairs of brackets like:
"one" <tab> "two three" ( four "five six" )

Want fields like:
field1:one
field2:two three
field3:four

field1:one
field2:two three
field3:four
field4:five six

Thanks much!!

--
William Stacey, MVP
Nov 16 '05 #1
7 10236
Should clarify a little. Basically, want to split a line that ignores all
whitespace (space, tab) except if the space is inclosed in quotes. Anything
in a quote pair is one field. A non-escaped quote (i.e. \") that does not
have a closing quote is an error. Same with the "(" parens. If paren in
not inside a quote, then it is special and needs a closing paren. If the
paren stuff makes this too hard, forget it and please help with the first
requirement. Again thanks!

--
William Stacey, MVP

"William Stacey [MVP]" <st***********@ mvps.org> wrote in message
news:#z******** *****@TK2MSFTNG P09.phx.gbl...
Would like help with a (I think) a common regex split example. Thanks for
your example in advance. Cheers!

Source Data Example:
one "two three" four

Optional, but would also like to ignore pairs of brackets like:
"one" <tab> "two three" ( four "five six" )

Want fields like:
field1:one
field2:two three
field3:four

field1:one
field2:two three
field3:four
field4:five six

Thanks much!!

--
William Stacey, MVP


Nov 16 '05 #2
I think it's a common match example, but not a common split example.
split assumes you have a single regex that matches the splitting text,
but you don't, since the text between *one* and *two* must start and end
with a double quote because there's one before *one*.

you can, however, match something like

(("\[^"]+")|(\w+))( \<[^>]*\>)*

and iterate on the matches.
HTH

William Stacey [MVP] wrote:
Should clarify a little. Basically, want to split a line that ignores all
whitespace (space, tab) except if the space is inclosed in quotes. Anything
in a quote pair is one field. A non-escaped quote (i.e. \") that does not
have a closing quote is an error. Same with the "(" parens. If paren in
not inside a quote, then it is special and needs a closing paren. If the
paren stuff makes this too hard, forget it and please help with the first
requirement. Again thanks!

Nov 16 '05 #3
Thanks Uri. However I need to preserve an arg like "this is one arg" as one
field and not have that four fields as I can't figure out after the fact
that that was one argument. Probably have to manually parse this, but
thought there may be easy way using regex. Cheers!

--
William Stacey, MVP

"Uri Dor" <re************ ***@mivzak.com> wrote in message
news:#T******** ******@tk2msftn gp13.phx.gbl...
I think it's a common match example, but not a common split example.
split assumes you have a single regex that matches the splitting text,
but you don't, since the text between *one* and *two* must start and end
with a double quote because there's one before *one*.

you can, however, match something like

(("\[^"]+")|(\w+))( \<[^>]*\>)*

and iterate on the matches.
HTH

William Stacey [MVP] wrote:
Should clarify a little. Basically, want to split a line that ignores all whitespace (space, tab) except if the space is inclosed in quotes. Anything in a quote pair is one field. A non-escaped quote (i.e. \") that does not have a closing quote is an error. Same with the "(" parens. If paren in not inside a quote, then it is special and needs a closing paren. If the paren stuff makes this too hard, forget it and please help with the first requirement. Again thanks!


Nov 16 '05 #4
Here is a cool little method that I modifed from a VB example. Does exactly
what I wanted. Can split on any delimiter or multiple delimiters and can
quote using any pair or chars. Very cool. Have not tested all possible
failures, etc, but appears to work well. Some clever (and generous) pattern
person may want to modify this to allow an *array of quote pairs, so you
could quote on "one two" or {one two} or (one two) in the same call. If you
do, please post update. Cheers!
==
/// <summary>
/// Split a string, dealing correctly with quoted items.
/// The quotes parm is the character pair used to quote strings
/// (default is "", the double quote).
/// You can also use a character pair (eg "{}") if the opening
/// and closing quotes are different.
///
/// For example, you can split the following string:
/// string[] fields = SplitQuoted("[one,two],three,[four,five]", , "[]")
/// into 3 items, because commas inside [] are not taken into account.
/// </summary>
/// <remarks>
/// Multiple seperators are ignored, so splitting "a,,b" using a comma as
/// the seperator will return two fields, not three. To get this behavior,
/// you could use ", " (comma and space) as seperators and default quotes.
/// Then set the string to something like ' a, "", b ' to get the empty
field.
/// You could also use comma as *only seperator and put a space to get a
space field
/// like 'a, ,b'.
/// </remarks>
/// <param name="text">str ing to split</param>
/// <param name="seperator ">The seperator char(s) as string.</param>
/// <param name="quotes">T he char pair used to quote a string.</param>
/// <returns>stri ng[]</returns>
private string[] SplitQuoted(str ing text, string seperators, string quotes)
{
// Default seperators is a space and tab (e.g. " \t").
// All seperators not inside quote pair are ignored.
// Default quotes pair is two double quotes ( e.g. '""' ).
if ( text == null )
throw new ArgumentNullExc eption("text", "text is null.");
if ( seperators == null || seperators.Leng th < 1 )
seperators = " \t";
if ( quotes == null || quotes.Length < 1 )
quotes = "\"\"";
ArrayList res = new ArrayList();

// Get the open and close chars, escape them for use in regular
expressions.
string openChar = Regex.Escape(qu otes[0].ToString());
string closeChar = Regex.Escape(qu otes[quotes.Length - 1].ToString());
// Build the pattern that searches for both quoted and unquoted elements
// notice that the quoted element is defined by group #2
// and the unquoted element is defined by group #3.
string pattern = @"\s*(" + openChar + "([^" + closeChar + "]*)" +
closeChar + @"|([^" + seperators + @"]+))\s*";

// Search the string.
foreach ( System.Text.Reg ularExpressions .Match m in
System.Text.Reg ularExpressions .Regex.Matches( text, pattern) )
{
string g3 = m.Groups[3].Value;
if ( g3 != null && g3.Length > 0 )
res.Add(g3);
else
{
// get the quoted string, but without the quotes.
res.Add(m.Group s[2].Value);
}
}
return (string[])res.ToArray(ty peof(string));
}

Nov 16 '05 #5
Hi William,

I am glad you got what you want. Do you still have any concern on this
issue?

Please feel free to feedback. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 16 '05 #6
Yes thanks. Here is a ~better one that will escape "\" anything, including
a quote inside quote pairs:
public static string[] SplitQuoted(str ing text, string seperators)
{
// "([^"\\]*(\\.[^"\\]*)*)"
// |
// ([^\s,]+)
// Default seperators is a space and tab (e.g. " \t").
// All seperators not inside quote pair are ignored.
// Default quotes pair is two double quotes ( e.g. '""' ).
if ( text == null )
throw new ArgumentNullExc eption("text", "text is null.");
if ( seperators == null || seperators.Leng th < 1 )
seperators = " \t"; // Default is space and tab.

// if ( quotes == null || quotes.Length < 1 )
// quotes = "\"\"";
ArrayList res = new ArrayList();

// Get the open and close chars, escape them for use in regular
expressions.
// string openChar = Regex.Escape(qu otes[0].ToString());
// string closeChar = Regex.Escape(qu otes[quotes.Length - 1].ToString());
// Build the pattern that searches for both quoted and unquoted elements
// notice that the quoted element is defined by group #2
// and the unquoted element is defined by group #3.
//| \s*("([^"]*)"|([^,]+))\s* |
// match any spaces upto first quote. that does not contain zero or more
" chars
// ending in a quote OR not one or more commas
// string pattern = @"\s*(" + openChar + "([^" + closeChar + "]*)" +
// closeChar + @"|([^" + seperators + @"]+))\s*";

//"([^"\\]*[\\.[^"\\]*]*)" //Note quotes at either end are required.
//|
//([^\s,]+)
//string[] sa = Regex.Split("my string", "pattern");
string pattern =
@"""([^""\\]*[\\.[^""\\]*]*)""" +
"|" +
@"([^" + seperators + @"]+)";

// Search the string.
foreach ( System.Text.Reg ularExpressions .Match m in
System.Text.Reg ularExpressions .Regex.Matches( text, pattern) )
{
//string g0 = m.Groups[0].Value;
string g1 = m.Groups[1].Value;
string g2 = m.Groups[2].Value;
if ( g2 != null && g2.Length > 0 )
{
res.Add(g2);
}
else
{
// get the quoted string, but without the quotes in g1;
res.Add(g1);
}
}
return (string[])res.ToArray(ty peof(string));
}

--
William Stacey, MVP

""Jeffrey Tan[MSFT]"" <v-*****@online.mi crosoft.com> wrote in message
news:br******** ******@cpmsftng xa10.phx.gbl...
Hi William,

I am glad you got what you want. Do you still have any concern on this
issue?

Please feel free to feedback. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.


Nov 16 '05 #7
Hi William,

Thanks for sharing your information with the community!!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 16 '05 #8

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

Similar topics

2
1433
by: Frank Oquendo | last post by:
I have the following code: string pattern = @"(\{)|(})|(\()|(\))|(\)|(\^)|(\*)|(/)|(-)|(\+)|(%)"; Regex regex = new Regex(pattern); string input = "QTY * ESTIMATED COST + 2"; string tokens = regex.Split(input); for (int i = 0; i != tokens.Length; i++) { Console.WriteLine("Token {0} = {1}", i, tokens.Trim());
4
728
by: William Stacey [MVP] | last post by:
Would like help with a (I think) a common regex split example. Thanks for your example in advance. Cheers! Source Data Example: one "two three" four Optional, but would also like to ignore pairs of brackets like: "one" <tab> "two three" ( four "five six" ) Want fields like:
5
1436
by: Jianwei Sun | last post by:
string sTest="TEST1||TEST2"; string asTest =Regex.Split(sTest, "||" ); I want to get an array with two elements TEST1 and TEST2, but it returs every char inside the sTest as a seperate array element. Thanks, Jianwei
3
6041
by: Rico | last post by:
If there are consecutive occurrences of characters from the given delimiter, String.Split() and Regex.Split() produce an empty string as the token that's between such consecutive occurrences. It sounds like making sense, but has anyone ever found this useful? Can this 'feature' be disabled? After having used StringTokenizer from the J-language that's not to be named, it's annoyed me for hours before I figured out that it was just a...
3
1740
by: Stephan Bour | last post by:
I have a string ³Name² in the following format: ³LastName, FirstName (Department)² that comes from Active Directory. I need to extract the FirstName from the string. Substrings are not practical for this so I used a Regex that splits the string at the first ³, ³ and again at the ³ (³. My problem is that I don¹t know how to extract the second member of the resulting array (FirstName) and assign it to another string. Using StringBuilder, as...
10
1526
by: Claud Balls | last post by:
I am splitting large files based on a text delimeter, but I don't want the delimeter left out of the string. For example if I had a string "NAME: Bill TOWN: Helena NAME: Frank TOWN: Helena" I would want to split on NAME: giving me s(0) = NAME: Bill TOWN: Helena s(1) = NAME: Frank TOWN: Helena *** Sent via Developersdex http://www.developersdex.com *** Don't just participate in USENET...get rewarded for it!
7
2267
by: lgbjr | last post by:
Hi All, I'm trying to split a string on every character. The string happens to be a representation of a hex number. So, my regex expression is (). Seems simple, but for some reason, I'm not getting the results I expect. Dim SA as string() Dim S as string S="FBE"
7
2232
by: Jordi Rico | last post by:
Hi, I know I can split a string into an array doing this: Dim s As String()=Regex.Split("One-Two-Three","-") So I would have: s(0)="One" s(1)="Two"
1
3304
by: mad.scientist.jr | last post by:
I am working in C# ASP.NET framework 1.1 and for some reason Regex.Split isn't working as expected. When trying to split a string, Split is returning an array with the entire string in element and an empty string in element . I am trying two different ways (an ArrayList and a string array) and both are doing that. Also, IndexOf is not working, but StartsWith does. The code:
0
10125
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
9962
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
11281
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
10649
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...
0
9851
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8207
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
7377
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();...
0
6282
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3495
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.