我必须将一行文本分成几个单词,并且对使用什么regex感到困惑。我到处寻找匹配一个单词的正则表达式,找到了类似于这篇文章的正则表达式,但我想在java中使用它(java不能处理常规字符串)。
Regex to match words and those with an apostrophe
我已经尝试了每个答案的正则表达式,但不确定如何为此构造一个java的正则表达式(我假设所有的正则表达式都是相同的)。如果在我看到的正则表达式中将\替换为\,则正则表达式不起作用。
我自己也试着去查了一下,结果打开了这个页面:http://www.regular-expressions.info/reference.html
但是我无法理解正则表达式的高级技术。
我使用String.split(这里是正则表达式字符串)来分隔字符串。举个例子,如果我被告知:“我喜欢吃,但我不喜欢吃每个人的食物,否则他们会饿死的。”我想要匹配:
I
like
to
eat
but
I
don't
like
to
eat
everyone's
food
or
they'll
starve我也不想匹配“”或“.”或其他排列。我的分隔符条件应该类似于:匹配任何单词字符
我得到的只是一个简单的正则表达式,它匹配单词\w,但我不确定如何使用先行或后视来匹配撇号,然后匹配其余的单词。
发布于 2012-11-30 03:26:42
在我的评论中提到的页面上,使用answer from WhirlWind,您可以执行以下操作:
String candidate = "I \n"+
"like \n"+
"to "+
"eat "+
"but "+
"I "+
"don't "+
"like "+
"to "+
"eat "+
"everyone's "+
"food "+
"'' '''' '.' ' "+
"or "+
"they'll "+
"starv'e'";
String regex = "('\\w+)|(\\w+'\\w+)|(\\w+')|(\\w+)";
Matcher matcher = Pattern.compile(regex).matcher(candidate);
while (matcher.find()) {
System.out.println("> matched: `" + matcher.group() + "`");
}它将打印:
> matched: `I`
> matched: `like`
> matched: `to`
> matched: `eat`
> matched: `but`
> matched: `I`
> matched: `don't`
> matched: `like`
> matched: `to`
> matched: `eat`
> matched: `everyone's`
> matched: `food`
> matched: `or`
> matched: `they'll`
> matched: `starv'e`你可以在这里找到一个运行的例子:http://ideone.com/pVOmSK
发布于 2012-12-02 10:08:42
下面的正则表达式似乎正确地覆盖了您的示例字符串。但它没有涵盖撇号的场景。
[\s,.?!"]+Java代码:
String input = "I like to eat but I don't like to eat everyone's food, or they'll starve.";
String[] inputWords = input.split("[\\s,.?!]+");如果我没理解错的话,撇号应该留在一个单词字符之后。下一个正则表达式应该涵盖上述内容以及撇号的特殊情况。
(?<!\w)'|[\s,.?"!][\s,.?"'!]*Java代码:
String input = "I like to eat but I don't like to eat everyone's food, or they'll starve.";
String[] inputWords = input.split("(?<!\\w)'|[\\s,.?\"!][\\s,.?\"'!]*");如果我对字符串运行第二个正则表达式:Hey there! Don't eat 'the mystery meat'.,我会在字符串数组中得到以下单词:
Hey
there
Don't
eat
the
mystery
meat'https://stackoverflow.com/questions/13632679
复制相似问题