I'm trying to figure out the regexp to match all the occurences of *this kind of strings*
. Two additional rules unfortunately made this thing more complicated than I thought:
*
followed by non-whitespace character (so * this one*
should not be matched*
followed by whitespace (so *this one *
and *this o*ne
should not be matchedI started with simplest regexp \*\S([^\*]+)?\*
which for my testing string:
*foo 1 * 2 bar* foo *b* azz *qu **ux*
matches places in square brackets:
[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]
and this is what I'd like to achieve:
[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]
so 2 problems appear:
*
followed by whitespace appears"? positive lookahead?\*\S([^\*]+)?\*\s
would do?If you want to start matching from the rightmost *
, you may use
\*(?=[^\s*]).*?(?<=[^\s*])\*(?!\S)
To start a match from a left-most *
(as in ``), remove the *
from the first lookaround (or replace its pattern with \S
):
\*(?=\S).*?(?<=[^\s*])\*(?!\S)
See the regex demo #1 and regex demo #2. Add (?s)
at the start or compile with Pattern.DOTALL
to match texts across lines.
Details
\*
- a *
char(?=[^\s*])
- the next char must be a non-whitespace and not a *
.*?
- any 0+ chars as few as possible(?<=[^\s*])
- the preceding char should be a non-whitespace and not a *
\*
- a *
char(?!\S)
- a whitespace boundary pattern, the next char can be a whitespace, or end of string can be at this location in the string.In Java:
String regex = "\\*(?=[^\\s*]).*?(?<=[^\\s*])\\*(?!\\S)";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With