I have been trying to come up with a regex for Java to match a bot command:
!x play search words here
where the x can be any alphanumeric character and it works with:
"(?:\\w)(\\w+)"
However if I want to use alias "p" for "play", the regex will skip the "p" also. I've been also trying to get the skip match to work with exclamation mark without success.
One workaround I found was to use:
"[^\\!\\w]+(\\w+)"
but then the first match is " p" with whitespace. I just can't figure this out!
To avoid matching words preceded with !
, you may use
"\\b(?<!!)\\w+"
See the regex demo
Details:
\b
- word boundary(?<!!)
- a negative lookbehind making sure there cannot be !
right before the current position\w+
- 1 or more word chars.Note that lookbehinds are zero-width assertions, they just signal the regex engine whether to go on matching or stop (the text matched does not get added to the current matched text).