-1

New to Regex so bear with me. I want to insert an "H" at the beginning of a string if the first character is not an "H". If it is an "H" then I would leave it alone. I'm working under Regex .net

For example...

Input H123456789 Ouput H123456789

Input 123456789 Output H123456789

Input ABCDE Output HABCDE

Thanks

I don't know enough about Regex to include anything helpful here

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • 2
    Why regex? Simply check first character and prepend H if needed. Regex is relatively expensive compared to such primitive approaches. – ZorgoZ Jul 18 '19 at 20:25
  • You can use tools and documentation to help you with Regex. I think many C# developers like LINQPad. In LINQPad there is a Regex helper. I let you search it on Bing. – Bastien Vandamme Jul 19 '19 at 01:31
  • Possible duplicate of [Regex - Does not contain certain Characters](https://stackoverflow.com/questions/4105956/regex-does-not-contain-certain-characters) – Bastien Vandamme Jul 19 '19 at 01:32

2 Answers2

0

If you want to evaluate if yous string not start with a specific character you can use

Regex.Matches(input, @"^[^H].*");

To replace you can evaluate the result of your Matches and use string.Concat or any other technique.

string input = "123456789";
if (Regex.IsMatch(input, @"^[^H].*"))
    input = string.Concat('H', input);

Console.WriteLine(input);
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
-1

The question is, why would you use REGEX?

A ternary 'if' would solve your problem easily.

string value = "123456";
value = value[0].Equals('H')? value : string.Concat("H",value);

REGEX is not that performative and I would only use it in a more complex situation.

Please do note that this code would only check for capital 'H', 'h' would not work properly. But an 'or' would solve it.

  • No the question is "Regex .net Insert Character in Start Of String If Not a specific Character". The comment you can add is "why would you use REGEX". – Bastien Vandamme Jul 19 '19 at 01:18
  • unfortunately, I'm an end user and Regex is the only way I can manipulate the data and I don't really want to start an IT Project for this as it's time sensitive and they have a backlog. I was hoping someone would have a solution for me within the Regex umbrella. Thanks. – Bryan Wheeler Jul 19 '19 at 14:54
  • @BryanWheeler Oh, I see. Sorry 'bout that, – Raphael Maia Ribeiro Jul 19 '19 at 17:43