热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用正则表达式从句子中找到[a-zA-Z]的单词-findingwordswith[a-zA-Z]fromasentenceusingRegex

Imtryingtogetallthewordsinasentencewithregexbutonlytheoneswith[a-zA-Z].SoforI

I'm trying to get all the words in a sentence with regex but only the ones with [a-zA-Z]. So for "I am a boy" I want {"I", "am", "a", "boy"} but for "I a1m a b*y", I want {"I", "a"} because "a1m" and "b*y" includes characters other than [a-zA-Z].

我试图用正则表达式得到一个句子中的所有单词,但只有[a-zA-Z]的单词。因此,对于“我是男孩”,我想要{“我”,“我是”,“一个”,“男孩”}但是对于“我a1m ab * y”,我想要{“我”,“一个”}因为“ a1m“和”b * y“包括[a-zA-Z]以外的字符。

So for me to get words, I'm trying to check

所以对我来说,我正试图检查

  1. if it's at the beginning of the string, then I only check if there's space after word
  2. 如果它在字符串的开头,那么我只检查是否有空格

  3. else there's a space before and after the word
  4. 否则这个词之前和之后都有一个空格

  5. if it's the last word, then check if there's space before the word.
  6. 如果它是最后一个单词,那么检查单词前面是否有空格。

So I ended up with something like this in Java:

所以我在Java中得到了类似的东西:

Pattern p = Pattern.compile("^[a-zA-Z]+ |^[a-zA-Z]+$| [a-zA-Z]+$| [a-zA-Z]+");
Matcher m = p.matcher("i am good");
while(m.find()) System.out.println(m.group());

However, I only get "i " and " good". Because when I'm getting "i ", there's one space after "i". So the string left is "am good" Since "am" is not at the beginning of the string, nor does it have a space before the word, it does not get returned.

但是,我只能得到“我”和“好”。因为当我得到“我”时,“i”之后有一个空格。因此,左边的字符串是“很好”因为“am”不在字符串的开头,也没有在单词之前有空格,所以它不会被返回。

Can you guys provide any feedback on this? Is there a way to just peek at the next character and not return the space?

你们能提供任何反馈意见吗?有没有办法只是偷看下一个角色而不是返回空间?

3 个解决方案

#1


6  

Assuming your regex engine supports lookahead/lookbehind assertions, you can use something like the following:

假设您的正则表达式引擎支持前瞻/后瞻断言,您可以使用以下内容:

(^|(?<= )[a-zA-Z]+($|(?= ))

Here's a quick description of what each component does:

以下是每个组件的功能的简要说明:

(^|(?<= )): This says "if a word starts here, we're interested". Specifically,
  ^: Match the beginning of the line, or
  (?<= ): Match any point that is preceded by a space, without actually consuming the space itself. This is called a positive lookbehind assertion.

(^ |(?<=)):这说“如果一个词从这里开始,我们就会感兴趣”。具体来说,^:匹配行的开头,或(?<=):匹配任何以空格开头的点,而不实际占用空间本身。这被称为积极的后视断言。

[a-zA-Z]+: This should be obvious, but it matches any run of sequential ASCII alphabetic characters.

[a-zA-Z] +:这应该是显而易见的,但它匹配任何连续的ASCII字母字符。

($|(?= )): This says "if the word is finished here, we're done". Specifically,
  $: Match the end of the line, or
  (?= ): Match any point that is followed by a space, without actually consuming the space itself. This is called a positive lookahead assertion.

($ |(?=)):这说“如果这个词在这里完成,我们就完成了”。具体来说,$:匹配行的结尾,或(?=):匹配任何后跟空格的点,而不实际占用空间本身。这被称为积极的先行断言。


Note that this particular regex doesn't count a word as a word if it's followed by punctuation. This may actually not be what you want, but you described checking for spaces so that's what the regex does. If you want to support words that are followed by simple punctuation you might amend that last atom to be

请注意,如果单词后跟标点符号,则此特定正则表达式不会将单词计为单词。这实际上可能不是你想要的,但你描述了检查空格,这就是正则表达式所做的。如果你想支持简单标点符号后面的单词,你可以修改最后一个原子

($|(?=[ .,!?]))

which will match the word if it's followed by a space, period, comma, exclamation mark, or question mark. You can be more elaborate too if you want.

如果后跟空格,句号,逗号,感叹号或问号,则会匹配该单词。如果你愿意,你也可以更精细。

#2


2  

Could you use a simpler pattern like \b[A-Za-z]+\b instead? (The \b metacharacter separates word characters (e.g., letters) from nonword characters (e.g., spaces and punctuation.))

您可以使用更简单的模式,例如\ b [A-Za-z] + \ b吗? (\ b元字符将单词字符(例如,字母)与非单词字符(例如,空格和标点符号)分开。))

The code

Pattern p = Pattern.compile("\\b[A-Za-z]+\\b");
Matcher m = p.matcher("i am good");
while(m.find()) System.out.println(m.group());

Produces {"i", "am", "good"} .

产生{“i”,“am”,“good”}。

Edit As mathematical.coffee commented, the above fails. The expression

编辑如math.coffee评论,上述内容失败。表达方式

(?<=^|\s)[A-Za-z]+(?=\W*(?:\s*$|\s))

may work better. For the string I a1m a b*y boy am is!! or, matching produces "I", "a", "boy", "am", "is", "or".

可能会更好。对于字符串我a1m a b * y boy am is !!或者,匹配产生“I”,“a”,“boy”,“am”,“is”,“or”。

If in the previous expression "is!!" should be ignored, the expression (?<=^|\s)[A-Za-z]+(?=$|\s) can be used instead. In the previous example, it does not return "is" but returns the other words (I, a, boy, am, or).

如果在前一个表达式中“是!!”应该忽略,可以使用表达式(?<= ^ | \ s)[A-Za-z] +(?= $ | \ s)代替。在前面的示例中,它不返回“is”但返回其他单词(I,a,boy,am或)。

#3


0  

This is just a note, if you didn't want to use something like Kevin Ballard has suggested. You can break the string into tokens and from there you can check each token to make sure it only contains only [a-zA-Z].

如果您不想使用Kevin Ballard建议的内容,这只是一个注释。您可以将字符串分解为标记,然后可以检查每个标记以确保它仅包含[a-zA-Z]。

To break it into tokens, do something like this:

要将其分解为令牌,请执行以下操作:

String message="The text of the message to be scanned.";
StringTokenizer st=new StringTokenizer(message);
while (st.hasMoreTokens())
    {
      checkWord(st.nextToken()); 
       idx++;
    }

And then you would write a function to check if that token is composed of [a-zA-Z]. Since there will be no white space to deal with, I think you'll find it much easier to deal with these tokens rather than the full string.

然后你会编写一个函数来检查该标记是否由[a-zA-Z]组成。由于没有空白处理空间,我认为你会发现处理这些令牌而不是完整的字符串要容易得多。

Best of luck.

祝你好运。


推荐阅读
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 深度学习中的Vision Transformer (ViT)详解
    本文详细介绍了深度学习中的Vision Transformer (ViT)方法。首先介绍了相关工作和ViT的基本原理,包括图像块嵌入、可学习的嵌入、位置嵌入和Transformer编码器等。接着讨论了ViT的张量维度变化、归纳偏置与混合架构、微调及更高分辨率等方面。最后给出了实验结果和相关代码的链接。本文的研究表明,对于CV任务,直接应用纯Transformer架构于图像块序列是可行的,无需依赖于卷积网络。 ... [详细]
  • OO第一单元自白:简单多项式导函数的设计与bug分析
    本文介绍了作者在学习OO的第一次作业中所遇到的问题及其解决方案。作者通过建立Multinomial和Monomial两个类来实现多项式和单项式,并通过append方法将单项式组合为多项式,并在此过程中合并同类项。作者还介绍了单项式和多项式的求导方法,并解释了如何利用正则表达式提取各个单项式并进行求导。同时,作者还对自己在输入合法性判断上的不足进行了bug分析,指出了自己在处理指数情况时出现的问题,并总结了被hack的原因。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 本文详细介绍了Python中正则表达式和re模块的使用方法。首先解释了转义符的作用,以及如何在字符串中包含特殊字符。然后介绍了re模块的功能和常用方法。通过学习本文,读者可以掌握正则表达式的基本概念和使用技巧,进一步提高Python编程能力。 ... [详细]
author-avatar
ze602
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有