我有这样一句话:
String str = " And God said, <sup>c</sup>“Let there be light,” and there was light.";我如何检索句子中的所有单词,期待下面的内容?
And
God
said
Let
there
be
light
and
there
was
light发布于 2016-04-16 22:53:53
首先,去掉任何前导或尾随空格:
.trim()然后去掉HTML实体(&...;):
.replaceAll("&.*?;", "")&和;是正则表达式中的文字字符,.*?是“任意字符、任意次数”的非贪婪版本。
接下来,去掉标签和它们的内容:
.replaceAll("<(.*?)>.*?</\\1>", "")<和>将再次从字面上理解,上面解释了.*?,(...)定义了捕获组,\\1引用了该组。
最后,对任意非字母序列进行拆分:
.split("[^a-zA-Z]+")[a-zA-Z]表示从a到z和A到Z的所有字符,^表示反转匹配,+表示“一次或多次”。
所以所有东西加在一起就是:
String words = str.trim().replaceAll("&.*?;", "").replaceAll("<(.*?)>.*?</\\1>", "").split("[^a-zA-Z]+");请注意,这不像<img src="a.png" />那样处理自动结束标记。
还要注意的是,如果你需要完整的超文本标记语言解析,你应该考虑让一个真正的引擎来解析它,比如parsing HTML with Regex is a bad idea。
发布于 2016-04-16 22:57:14
您可以将String.replaceAll(正则表达式,替换)与正则表达式^A-Za-z+一起使用,这样只获取字符。这也将包括sup标记和c。这就是为什么您要用第一个语句替换标记以及它们之间的所有内容。
String str = " And God said, <sup>c</sup>“Let there be light,” and there was light.".replaceAll("<sup>[^<]</sup>", "");
String newstr = str.replaceAll("[^A-Za-z]+", " ");https://stackoverflow.com/questions/36665402
复制相似问题