Node.js 如何找到含有大写字母的单词
Node.js 是一个开源的、跨平台的运行时环境,用于在浏览器之外执行JavaScript代码。它被广泛用于为小到大型公司开发API和微服务。
单数词: 单数名词是指只指一个人、地方、事物或概念的名词。与之相对的是复数名词,表示多于一个人、地方、事物或概念。单数名词的示例是程序员,代表一个程序员;复数名词的示例是程序员们,代表两个或更多程序员。
要找到一个含有大写字母的单词,首先需要找到含有大写字母的词,然后检查这些大写词是否是单数形式。
正则表达式: 正则表达式是一种用于在文本中搜索和匹配模式的工具。它通常用于编程语言中搜索和操作字符串。正则表达式可以用于查找特定的单词或字符,也可以用于确保字符串遵循特定的格式,比如电子邮件地址或电话号码。
查找单词: 要查找含有大写字母的词,我们可以使用String对象的match()函数。该函数在字符串中搜索与正则表达式匹配的内容,并返回包含搜索结果的数组。
示例1:
const string = "Peoples said that, John is good boy";
console.log(`Words with capital letter in string : ${string}`);
const regex = /\b[A-Z][A-Za-z]*\b/g;
const result = string.match(regex);
console.log(result);
输出:
Words with capital letter in string : Peoples said that, John is good boy
[ 'Peoples', 'John' ]
确定单数还是复数形式:
- 为了确定一个词的单数或复数形式,我们使用的是 pluralize 包,该包使用了先进的技术,如机器学习,来尝试确定单词的正确形式。
创建项目的设置: 按照以下步骤创建一个项目应用:
步骤1: 在一个新的文件夹中创建一个新的项目,使用以下命令:
npm init -y
步骤2: 安装-module pluralize
npm install pluralize --save
步骤3: 创建一个index.js文件
项目结构: 项目的结构应该如下所示:
示例1: 在下面的代码中,使用正则表达式来匹配给定字符串中以大写字母开头的所有单词。然后使用match()方法来查找给定字符串中这个正则表达式的所有匹配,从而得到一个以大写字母开头的单词数组。代码然后检查每个单词是否是单数形式,使用“pluralize”库的isSingular()方法,并将其添加到singulars数组中。
string : "Geek is a programmer"
- index.js文件:
// require module which is used to determine
// the singular or plural form of a word
const pluralize = require("pluralize");
const string = "Geek is a programmer";
// regex is used to find all the words
// which has capital letter in it
const regex = /\b[A-Z][A-Za-z]*\b/g;
const result = string.match(regex);
const singulars = [];
result.forEach((word) => {
// isSingular method of pluralize library
// to determine the singular form of a word
if (pluralize.isSingular(word)) {
singulars.push(word);
}
});
console.log("Singular Words which has capital letter in it ");
console.log(singulars); // ['Geek']
运行应用程序的步骤: 在终端中写下以下代码来运行应用程序:
node index.js
输出: