简体   繁体   中英

Regular Expression to replace a specific string

I have a string of the following format:

tablename.colname > [[2 | prompt and text]] and tabname.colname < [[1000| prompt
 or text]]

I need to replace the text within '[[]]' with the value before the pipe symbol. Right now,

i) i'm splitting the string with the logical operators such as AND and OR (Note: This also splits the 'and' within the square brackets, that i really don't want.)

ii) Then the resultant strings with the mathematical operators.

Can anyone help to find a regular expression to find the texts in between the double square brackets and replace it with the value before pipe symbol...

The value before the pipe can be integer or string.

Something like this should work

resultString = Regex.Replace(subjectString, @"(\[\[)(.*?)\|(.*?)(\]\])", "$1$2$4", RegexOptions.Multiline);

Input : [[2 | prompt and text]] and tabname.colname < [[1000| prompt or text]] [[2 | prompt and text]] and tabname.colname < [[1000| prompt or text]]

Output : [[2 ]] and tabname.colname < [[1000]]

Search for

\[\[([a-zA-Z0-9]+) ?\|.*?\]\]

Replace with

[$1]

Check it here

A brief explanation

\[\[                 - The starting [[
([a-zA-Z0-9]+)       - Match any number of letters and digits (made a capturing group)
 ?                   - An optional space
\|                   - Pipe symbol
.*?                  - Match anything without been greedy
\]\]                 - Closing ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM