Reputation: 574
I'm trying to select all [a-z',]
symbols but exclude commas at start and end. Keep only the selection inside the red rect. How can I do this?
Upvotes: 1
Views: 1106
Reputation: 75850
I think what you want is an optional capturing group repeating zero or more times:
[a-z](?:[',]*[a-z]+)*
See the Online Demo
[a-z]
- A character in the range a-z.(?:
- Open non-capturing group.
[',]*
- Zero or more characters from the specified character class.[a-z]+
- At least one character in the range a-z.)*
- Close non-capturing group and match it zero or more times.Note: If for good reasons OP's intention was to match a quote at the very end, we can add an optional apostrophe: [a-z](?:[',]*[a-z]+'?)*
. See an online demo
Upvotes: 3
Reputation: 110675
You could match with the following regular expression.
[a-z'](?:[a-z',]*[a-z'])?
Start your engine!
Javascript's regex engine performs the following operations.
[a-z'] : match one character in character class
(?: : begin non-capture group
[a-z',]* : match 0+ characters in character class
[a-z'] : match one character in character class
) : end non-capture group
? : optionally match non-capture group
Upvotes: 1
Reputation: 43169
You could first replace the commas in question and select the characters you want afterwards:
let string = `,,."?!tats,t'ats,t,s',l,f,%$,`;
string = string.replace(/^,|,$/g, "~ooo~");
console.log(string);
In other languages you could use lookarounds (a negative lookbehind and a positive lookahead, that is).
Upvotes: 1