正则表达式 - 如何搜索单词的单数或复数版本 [英] Regex - How to search for singular or plural version of word

查看:33
本文介绍了正则表达式 - 如何搜索单词的单数或复数版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的正则表达式,我想做的就是匹配单词的单数部分,无论它的末尾是否有 s.所以如果我有以下的话

I'm trying to do what should be a simple Regular Expression, where all I want to do is match the singular portion of a word whether or not it has an s on the end. So if I have the following words

test
tests

进一步的例子,我需要这对很多词来说都是可能的,而不仅仅是那两个

Further examples, I need to this to be possible for many words not just those two

movie
movies
page
pages
time
times

对于他们所有人,我都需要得到结尾不带 s 的单词,但我找不到一个正则表达式,它总是会抓取第一位而结尾不带 s 并且适用于这两种情况的正则表达式.

For all of them I need to get the word without the s on the end but I can't find a regular expression that will always grab the first bit without the s on the end and work for both cases.

我尝试了以下方法:

([a-zA-Z]+)([s\b]{0,}) - This returns the full word as the first match in both cases
([a-zA-Z]+?)([s\b]{0,}) - This returns 3 different matching groups for both words
([a-zA-Z]+)([s]?) - This returns the full word as the first match in both cases
([a-zA-Z]+)(s\b) - This works for tests but doesn't match test at all
([a-zA-Z]+)(s\b)? - This returns the full word as the first match in both cases

我一直在使用 http://gskinner.com/RegExr/ 来尝试不同的正则表达式.

I've been using http://gskinner.com/RegExr/ for trying out the different regex's.

这是一个崇高的文本片段,对于那些不知道崇高文本中的片段的人来说,这是一个快捷方式,这样我就可以输入我的数据库名称并点击运行片段",它会转它变成了类似的东西:

This is for a sublime text snippet, which for those that don't know a snippet in sublime text is a shortcut so that I can type say the name of my database and hit "run snippet" and it will turn it into something like:

$movies= $this->ci->db->get_where("movies", "");
if ($movies->num_rows()) {
    foreach ($movies->result() AS $movie) {

    }
}

我需要的只是将电影"变成电影"并自动将其插入到 foreach 循环中.

All I need is to turn "movies" into "movie" and auto inserts it into the foreach loop.

这意味着我不能只对文本进行查找和替换,我只需要考虑 60 - 70 个单词(它只针对我自己的表格,而不是英语中的每个单词).

Which means I can't just do a find and replace on the text and I only need to take 60 - 70 words into account (it's only running against my own tables, not every word in the english language).

谢谢!- 蒂姆

推荐答案

好的,我找到了解决方案:

Ok I've found a solution:

([a-zA-Z]+?)(s\b|\b)

按需要工作,然后您可以简单地使用第一个匹配项作为单词的非复数形式.

Works as desired, then you can simply use the first match as the unpluralized version of the word.

感谢@Jahroy 帮我找到它.我将此添加为仅需要解决方案的未来冲浪者的答案,但请查看 Jahroy 的评论以获取更深入的信息.

Thanks @Jahroy for helping me find it. I added this as answer for future surfers who just want a solution but please check out Jahroy's comment for more in depth information.

这篇关于正则表达式 - 如何搜索单词的单数或复数版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆