-3

I want to understand how to create a regular expression which will match a set of words, where the nth letter is 'X', and the nth to last letter is 'Y'.

For example:

where 1st letter is f, and second to last letter is s:
fish -- MATCH
fashion -- NO MATCH
first -- MATCH

I have no attempts as I don't know where to start.

2
  • While this question may not confuse me, it might some others. Could you provide some word examples of what you want matched and not matched? Also any attempt you have tried?
    – hwnd
    Feb 25, 2015 at 23:18
  • Regex is about building patterns. Break what you want down into pieces and look for the regex matcher. For example, you want the start of the string to be f followed by any number of letters, followed by s, followed by exactly one more letter, and then the end of the string. (Replace start/end of string with word boundaries if each entry is not on its own line.)
    – Evan Davis
    Feb 25, 2015 at 23:50

1 Answer 1

0

Here's a starting point:

/(.{0}f.*s.{1})\s/gU

Matches fish and first but not fashion. Example.

Explanation:

(...) - capture group
.{0}  - match anything zero times (in case you want to match something where the first letter is not at the start of the string
f     - match "f" literally
.*    - match anything
s     - match "s" literally
.{1}  - match anything once (this means that "s" would be second to last in the string)
\s    - for example only in your test data block. You could substitute this for an EOL delimiter e.g. ^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.