正则表达式匹配一定长度的单词

正则表达式匹配一定长度的单词

本文介绍了正则表达式匹配一定长度的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道正则表达式匹配单词,使单词具有最大长度。
例如,如果一个单词的长度最多为10个字符,我希望正则表达式匹配,但如果长度超过10,则正则表达式不匹配。

I would like to know the regex to match words such that the words have a maximum length.for eg, if a word is of maximum 10 characters in length, I would like the regex to match, but if the length exceeds 10, then the regex should not match.

我试过

^(\w{10})$

但只有当单词的最小长度为10个字符时,才会给我带来匹配。如果单词超过10个字符,它仍然匹配,但只匹配前10个字符。

but that brings me matches only if the minimum length of the word is 10 characters. If the word is more than 10 characters, it still matches, but matches only first 10 characters.

推荐答案

我想你想要 \ w {1,10} \ b \ b 匹配单词边界。

I think you want \w{1,10}\b. The \b matches a word boundary.

当然,您也可以替换 \b 并执行 ^ \w {1,10} $ 。这将匹配最多10个字符的单词,只要它是字符串的唯一内容即可。我认为这就是你之前所做的。

Of course, you could also replace the \b and do ^\w{1,10}$. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.

因为它是Java,你实际上必须逃避反斜杠:\\瓦特{1,10} \\b。你可能已经知道了这一点,但它之前让我知道了。

Since it's Java, you'll actually have to escape the backslashes: "\\w{1,10}\\b". You probably knew this already, but it's gotten me before.

这篇关于正则表达式匹配一定长度的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:16