1

I need to do some modifications on dynamically generated strings;

String Example

Products [279] Electric Paint Sprayer [21] Airbrush Equipment [109] Spray Tanning Equipment [23] Mini Air Compressor [33] Sand blasting gun [5] Paint Tank [9] Air Spray Gun [26] Pneumatic tools/Air tools [26] Tire Inflating gun [10] Air Riveter [6] Hand Tools [7] Comb/Hair Brush [4]

I want to remove "Products [279]" from the beginning (always the same except the numbers) and replace the rest of the string like this "Electric Paint Sprayer [21] - Airbrush Equipment [109] - ..."

1
  • Do you really need Regex for such a simple task? have you tried this?str=str.Substring(str.IndexOf(']')+2) Commented Jan 6, 2012 at 22:14

3 Answers 3

1

Demo

String sample = @"Products [279] Electric Paint Sprayer [21] Airbrush Equipment [109] Spray Tanning Equipment [23] Mini Air Compressor [33] Sand blasting gun [5] Paint Tank [9] Air Spray Gun [26] Pneumatic tools/Air tools [26] Tire Inflating gun [10] Air Riveter [6] Hand Tools [7] Comb/Hair Brush [4]";

// Remove "Products [#] "
sample = Regex.Replace(sample, @"^Products \[\d+\]\s*", String.Empty);

// Add hyphens
sample = Regex.Replace(sample, @"(\[\d+\])(?=\s*\w)", @"$1 - ");
// the (?=\s*\w) makes sure we only add a hyphen when there's more information
// ahead (and not a hyphen to the end of the string)

Outcome:

Electric Paint Sprayer [21] - Airbrush Equipment [109] - Spray Tanning Equipment [23] - Mini Air Compressor [33] - Sand blasting gun [5] - Paint Tank [9] - Air Spray Gun [26] - Pneumatic tools/Air tools [26] - Tire Inflating gun [10] - Air Riveter [6] - Hand Tools [7] - Comb/Hair Brush [4]

Sign up to request clarification or add additional context in comments.

Comments

0

You can use String.Remove or String.Replace to do this. Remember that this does not modify that string but returns a new one.

Oh, and to find the Products [XXX], you could use String.SubString(0, String.IndexOf(']')); To find the string that includes the first instance of ']'.

Comments

0

Proceed as follows:

  • replace ^\w+\s+\[\d+\]\s+ with nothing (removes Products [279]<space> in your example);
  • replace (?<\])(?=\s+.) with <space>- globally.

1 Comment

thanks #fge, first one works but the second one gives me error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.