Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expressions

Status
Not open for further replies.

shades44

Programmer
Jun 14, 2004
25
CA
Hi,

I'm trying to use Regular Expressions to search for this pattern --> [#] (basically a number in square brackets). I cant seem to create the correct search string to do that.

I have this: string pattern = "[[](/d)[]]";

Any help would be much appreciated!

shady
 
this
Match MyRegMatch = Regex.Match(_input,@"^\[\d+\]$");
would match only [0-9] must be one or more numbers

this
Match MyRegMatch = Regex.Match(_input,@"^\w*\[\d+\]\w*$");
would match [0-9] inside 0 or more characters a-zA-Z0-9_

hth,
Marty
 
hi Marty,

what im trying to do is find occurences of [#] in a string and replace them with "" (delete them), for example,

string text = "the guy went[4] to china";
string pattern = ???
text = Regex.Replace(text, pattern, "");
text is now: "the guy went to china";

Neither one of @"^\[\d+\]$" or @"^\w*\[\d+\]\w*$" seemed to do that. I'm all out of ideas.

shady
 
i discovered something that i found very confusing.. i have this code..

when the input text is assigned programmatically and then inserted into the code :

string input = ....//code
input = Regex.Replace(input, @"\[\d+\]", "");

it doesnt find and remove [4], but when i find out what the actual string is and assign it literally it works:

string input = "the guy went[4] to china";
input = Regex.Replace(input, @"\[\d+\]", "");
input now is --> "the guy went to china"


why should there be any difference in the two scenarios? can anyone explain this

shady
 
shady, not sure what you mean, this is a small test stub that takes the string from the console input and writes it out and I also hard coded the line and got the same results.
Code:
using System;
using System.Text.RegularExpressions;
namespace StringTest
{
	class MainClass // Defining Class 
	{	
		public static void Main(string[] args) // Program Entry Point 
		{ 
			string _input;
			Console.Write("Enter string: ");
			_input = Console.ReadLine();
			while (!(_input.Equals("end")))
			{
				MainClass.mymatch(_input);
				Console.Write("Enter string: ");
				_input = Console.ReadLine();
			}				
		}
		public static void mymatch(string _input)
		{
//			_input = "the guy went[4] to china";
			_input = Regex.Replace(_input, @"\[\d+\]", "");
			Console.WriteLine(_input);
		}
	}
}
Marty
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top