1

I am in a situation that I need to extract words/variables from a string(expression). I tried to accomplish this. The following situation is valid:

OK/Test(ANSWER[12])+SUM(Test(ANSWER[..]))*OK+ANSWER[14] 

I need to extract the "OK" "variables". I managed to extract other components like ANSWER[..] e.g. These variables are dynamic ofcourse.

I already tried things like:

/[a-zA-Z]*(?!\(|\[)/g

But this also returns SU (From SUM, which is not desired)

Thanks in advance :)

Edit: clarification

I need to extract words that are only surrounded by whitespace (begin or end of string) or +-*/ operators. Words that have ()[] before or after them should be ignored.

2
  • I tried to explain myself better in a edit I did just make. I just use Regex.Matches(). So any C# code is irrelevant right? Commented Nov 13, 2019 at 8:49
  • 1
    The code is also relevant as you posted a regex literal and C# does not support this notation. Try @"(?<![^\s+*/-])\w+(?![^\s+*/-])" or @"(?<![^\s+*/-])[A-Za-z]+(?![^\s+*/-])" (depending on what the "word" is for you here). Commented Nov 13, 2019 at 8:50

1 Answer 1

1

You may use

(?<![^\s+*/-])\w+(?![^\s+*/-])

See the regex demo

Details

  • (?<![^\s+*/-]) - a whitespace boundary with +, -, / and * included
  • \w+ - 1+ word chars
  • (?![^\s+*/-]) - a whitespace boundary with +, -, / and * included

C# sample code:

var results = Regex.Matches(text, @"(?<![^\s+*/-])\w+(?![^\s+*/-])")
        .Cast<Match>()
        .Select(x => x.Value);
Sign up to request clarification or add additional context in comments.

Comments

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.