简体   繁体   中英

VB.Net regex add to string

I'm struggling with a regex expression in VB.Net. As I'm new to regex, I don't know how to go about this issue.

My goal is to build a calculator, and I want to be able to calculate sin, cos and tan. My input string for one of these calculations, for example, may be sin(93) + tan(2) + cos(364) + 5 * 3 .

I have used MathParser for the calculating, and that works fine, however by default MathParser uses radians, and I want the option to switch to decimal. I have a control on my form that sets a boolean isRad to false when the user selects decimal, and vise-versa. In order to use decimals in MathParser, the input string needs to become sin(93*[dec]) + tan(2*[dec]) + cos(364*[dec]) + 5 * 3 .

I've attempted to use regex to find where in the input code I have a sine, cos or tan function. I came up with (sin|cos|tan)\\(.?.?.?.?.?.?\\) , but I'm aware that this is a less than brilliant expression. Even if it was perfect, however, my question regards how to put the required *[rad] or *[dec] into the string. I've tried the following, but I just get (sin|cos|tan)\\(.?.?.?.?.?.?\\*[dec]) as output.

    Dim equationString As String = Regex.Replace("sin(93) + tan(2) + cos(364) + 5 * 3", "(sin|cos|tan)\(.?.?.?.?.?.?\)", "(sin|cos|tan) \ (.?.?.?.?.?.?*[" & Str_RadOrDec & "]\)")
    MsgBox(equationString)

You can use capturing groups, like this.

Dim equationString As String = Regex.Replace("sin(93) + tan(2) + cos(364) + 5 * 3", "(sin|cos|tan)(\(.?.?.?.?.?.?)(\))", "$1$2" + "*[" & Str_RadOrDec & "]$3")

https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.match.groups?view=netframework-4.7.2

A regular expression pattern can include subexpressions, which are defined by enclosing a portion of the regular expression pattern in parentheses. Every such subexpression forms a group. The Groups property provides access to information about those subexpression matches.

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