0

I need to have a .NET regex to match "[@foo]" from "applicant_data/contact_number[@foo]" w/c I can already do using the pattern "\[@(.*?)\]".

However I want to make an exception so that "applicant_data/contact_number[@foo=2]" does not match the pattern. So the question is what should be the regular expression so that it will get any valid alphanumeric ([@bar],[@theVar],[@zoo$6]) but not [@bar=1], [@theVar=3]?

5
  • And what have you tried? Commented Dec 18, 2017 at 9:50
  • [@(.*?)[^=2]] Commented Dec 18, 2017 at 9:52
  • Is the word foo constant or can it vary? Also, you want to exclude it only for the number 2 or any number? Commented Dec 18, 2017 at 9:55
  • @Sefe i've tried "[@(.*?)]" Commented Dec 18, 2017 at 9:59
  • @Gurman foo is not fixed it can vary Commented Dec 18, 2017 at 10:00

2 Answers 2

1

You may try this:

\[@[\w-]+(?!=)\]

the explanation:

"\[" &       ' Match the character “[” literally
"@" &        ' Match the character “@” literally
"[\w-]" &    ' Match a single character present in the list below
                ' A “word character” (Unicode; any letter or ideograph, digit, connector punctuation)
                ' The literal character “-”
   "+" &        ' Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"(?!" &      ' Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   "=" &        ' Match the character “=” literally
")" &
"\]"         ' Match the character “]” literally

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

any chance you could expand the answer as to only get "foo" from "@[foo]" meaning find a word character (without the "=" sign) preceded by "@[" and succeeded by "]".
i think i misunderstood your requirement... (?<=@\[)\w+(?=\])...this would match word-characters surrounded by @[ at start and by ] at end...
1

Try this regex:

\[@(?![^\]]*?=).*?\]

Click for Demo

Explanation:

  • \[@ - matches [@ literally
  • (?![^\]]*?=) - negative lookahead to make sure that = is not present anywhere before the next ]
  • .*? - matches 0+ occurrences of any character except a newline character
  • \] - matches ] literally

1 Comment

thanks @Gurman "=2" is not constant it could be "=bar". Frankly just detecting the presence of "=" sign inside "[@theWord]" would work.

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.