0

Im trying to find a regex that only matches any character in the beginning and any character after the pattern one time or no time. So XpatternY should match but also pattern alone should be a match. I tryied using [A-Z]?pattern[A-Z]? but this regex also recognizes XXpatternYY or anything else before and after pattern

Rick
  • 11
  • 4
  • 2
    Per rules in [tag:regex] tag, "Since regular expressions are not fully standardized, all questions with this tag should also include a tag specifying the applicable programming language or tool." In your case, the best tool is negative lookbehind and lookahead, but there are dialects lacking one or both of them (if I understood the question). Also, the question is ambiguous - would `"blahXpatternYblah"` match (as X and Y are not repeated)? or do you want at most one character before and after in the whole string? – Amadan Jun 13 '18 at 08:53
  • Try `^[A-Z]?pattern[A-Z]?$` – Bohemian Jun 13 '18 at 08:55
  • Your regex does the job. Thank you! – Rick Jun 13 '18 at 09:22

1 Answers1

0

You could use a word boundary:

\b[A-Z]?pattern[A-Z]?\b

Or use anchors ^ and $ to assert the start and the end of the line:

^[A-Z]?pattern[A-Z]?$

The fourth bird
  • 154,723
  • 16
  • 55
  • 70