Probably the posts from Mico's link are the best way to go, but here is an alternative that allows you to avoid typing the text twice: tikzmark. I actually do not think that this method is superior in this very case because
- you have to load another package,
- you need to insert a
\vphantom to get the vertical space right as an overlay tikzpicture does not insert space, and
- you need to give each
\tikzmarknode a unique label.
However, it is an alternative, and as soon as you want a more fancy bracket (bent, dashed, whatever) this method is likely to continue to give you what you want.
\documentclass{article}
\usepackage{mathtools}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\begin{document}
Some text to test the vertical space.
$
w = \vphantom{\overbracket[0.75pt]{a}^{x}}% to fix the vertical space
\underbracket[0.75pt]{aa\tikzmarknode{a1}{a}\dots a}{n}
\underbracket[0.75pt]{a\tikzmarknode{a2}{a}a\dots a}{m}
\underbracket[0.75pt]{bbb\dots b}{n}
\underbracket[0.75pt]{aaa\dots a}{m}
\underbracket[0.75pt]{bbb\dots b}_{n}
\begin{tikzpicture}[overlay,remember picture]
\draw[line width=0.75pt] (a1.north east) -- ++ (0,0.8ex)
-| node[pos=0.25,above]{$x$} (a2.north east);
\end{tikzpicture}
$
Some text to test the vertical space.
[w = \vphantom{\overbracket[0.75pt]{a}^{x}}% to fix the vertical space
\underbracket[0.75pt]{aa\tikzmarknode{a3}{a}\dots a}{n}
\underbracket[0.75pt]{a\tikzmarknode{a4}{a}a\dots a}{m}
\underbracket[0.75pt]{bbb\dots b}{n}
\underbracket[0.75pt]{aaa\dots a}{m}
\underbracket[0.75pt]{bbb\dots b}_{n}
\begin{tikzpicture}[overlay,remember picture]
\draw[line width=0.75pt] (a3.north east) -- ++ (0,0.8ex)
-| node[pos=0.25,above]{$x$} (a4.north east);
\end{tikzpicture}
]
Some text to test the vertical space.
\end{document}
