从字符串中提取单词的正则表达式

发布于 2024-09-07 14:45:38 字数 85 浏览 9 评论 0原文

我想从 java 字符串中提取所有单词。

单词可以用任何欧洲语言书写,并且不包含空格,仅包含字母符号。

但它可以包含连字符。

I want to extract all words from a java String.

word can be written in any european language, and does not contain spaces, only alpha symbols.

it can contain hyphens though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

压抑⊿情绪 2024-09-14 14:45:38

如果您不依赖正则表达式,还可以查看 BreakIterator,特别是 getWordInstance() 方法:

单词边界分析用于搜索和替换功能,以及允许用户通过双击选择单词的文本编辑应用程序。单词选择提供了对单词内及其后的标点符号的正确解释。不属于单词的字符(例如符号或标点符号)两侧都有分词符。

If you aren't tied to regular expressions, also have a look at BreakIterator, in particular the getWordInstance() method:

Word boundary analysis is used by search and replace functions, as well as within text editing applications that allow the user to select words with a double click. Word selection provides correct interpretation of punctuation marks within and following words. Characters that are not part of a word, such as symbols or punctuation marks, have word-breaks on both sides.

江南烟雨〆相思醉 2024-09-14 14:45:38

您可以使用 (? 的变体,即任何最大的非空白字符序列。

  • 使用否定查找,以便它可以匹配字符串开头和结尾的“单词”
  • 将您自己的字符类替换为 \S 以查找更具体的内容
    • (例如[A-Za-z-]等)

这是一个简单的例子来说明这个想法,使用[az-]作为字母字符类:

    String text = "--xx128736f-afasdf2137asdf-12387-kjs-23xx--";
    Pattern p = Pattern.compile(
        "(?<!alpha)alpha+(?!alpha)".replace("alpha", "[a-z-]")
    );
    Matcher m = p.matcher(text);
    while (m.find()) {
        System.out.println(m.group());
    }

这会打印:

--xx
f-afasdf
asdf-
-kjs-
xx--

参考文献


但是字母表应该是什么?

您可能必须使用 Unicode 字符类等(留在原地,现在研究主题)

You can use a variation of (?<!\S)\S+(?!\S), i.e. any maximal sequence of non-whitespace characters.

  • Negative lookarounds are used so that it can match "words" at the beginning and end of string
  • Substitute your own character class for \S to look for something more specific
    • (e.g. [A-Za-z-], etc)

Here's a simple example to illustrate the idea, using [a-z-] as the alphabet character class:

    String text = "--xx128736f-afasdf2137asdf-12387-kjs-23xx--";
    Pattern p = Pattern.compile(
        "(?<!alpha)alpha+(?!alpha)".replace("alpha", "[a-z-]")
    );
    Matcher m = p.matcher(text);
    while (m.find()) {
        System.out.println(m.group());
    }

This prints:

--xx
f-afasdf
asdf-
-kjs-
xx--

References


But what should the alphabet be?

You may have to use the Unicode character classes etc (stay put, researching on topic right now)

后eg是否自 2024-09-14 14:45:38

这将匹配一个单词:

`([^\s]+)`

This will match a single word:

`([^\s]+)`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文