简体   繁体   English

使用正则表达式计算字符串中句号和逗号的数量

[英]Count number of fullstops and commas in string using regex

I am trying to count the number of fullstops and commas in a sentence using a regex. 我正在尝试使用正则表达式计算句子中句号和逗号的数量。 The code I am using is the following. 我正在使用的代码如下。

var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length;
var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length;

This works for a comma count, however for the fullstop count it counts every character in the sentence. 这适用于逗号计数,但是对于句号计数,它计算句子中的每个字符。 Can anyone explain why this is happening and how to fix it. 谁能解释为什么会这样以及如何解决。

Please see below for the complete code: 请参见下面的完整代码:

 var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length; var fullStopCount = $("#text-input").val().match(new RegExp(".", "g")).length; $(".comma-count").text(", : " + commaCount); $(".fullstop-count").text(". : " + fullStopCount); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea> <p class="comma-count"></p> <p class="fullstop-count"></p> 

You need to escape . 你需要逃跑. using \\\\ , since . 使用\\\\ ,因为. matches any single character except the newline character in regex. 匹配正则表达式中除换行符以外的任何单个字符。

var fullStopCount = $("#text-input").val().match(new RegExp("\\.", "g")).length;

or use regex like 或使用正则表达式

var fullStopCount = $("#text-input").val().match(/\./g).length;

 var commaCount = $("#text-input").val().match(new RegExp(",", "g")).length; var fullStopCount = $("#text-input").val().match(new RegExp("\\\\.", "g")).length; $(".comma-count").text(", : " + commaCount); $(".fullstop-count").text(". : " + fullStopCount); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="text-input" name="textarea" rows="5" cols="50">There should only be, one full stop.</textarea> <p class="comma-count"></p> <p class="fullstop-count"></p> 

Try below : 请尝试以下方法:

var fullStopCount = $("#text-input").val().match(new RegExp(/\./g)).length;
var commaCount = $("#text-input").val().match(new RegExp(/\,/g)).length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM