Kevin Morrissey
Kevin Morrissey

Reputation: 179

How to replace "&A-Z" with the orinal text minus the &

I'm looking for a way to replace "&" from a text string when it's followed by text. For example;

Input Text: "Ne&w && Edit Record" Required Output: New & Edit Record"

The reason for "Ne&w" is that "&" then shows w as the shortcut key (underscored in the UI) and the reason for the "&&" is so that a single "&" is displayed in the text.

When using the input text as the value for the text propery on a command button the text displays as expected, but when I pass the text property to a message box it displays the input text in the message box dialog.

I don't want to use the Tag property to store the message I want in the message box as I use the tag property for another value.

Upvotes: 1

Views: 73

Answers (2)

Victor Zakharov
Victor Zakharov

Reputation: 26424

Try this:

Dim input As String = "Ne&w && Edit Record"
Dim output As String = "New & Edit Record"
Dim p As String = Regex.Replace(input, "&(?<first>\w|&)", "${first}")
MessageBox.Show(output = p) 'shows True

In the above Regex expression I am capturing an ampersand followed by either a letter or another ampersand, and replacing that sequence with a symbol coming after the ampersand. <first> is a named group, it is used for Regex replacement.

See Regex.Replace on MSDN.

Upvotes: 2

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

You can remove all & signs not followed by a & sign. Match them like this:

&(?!&)

See it in action

Upvotes: 1

Related Questions