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
Asked
Active
Viewed 2,399 times
0

Rick
- 11
- 4
-
2Per 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 Answers
0
You could use a word boundary:
Or use anchors ^
and $
to assert the start and the end of the line:

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