简体   繁体   English

javascript正则表达式排除字符

[英]javascript regex exclude character

I have text like this 我有这样的文字

ab:_c AB:_c

a:_c 答:_c

The regex that I am using is /:(.*)/g , but it also captures ':_' 我正在使用的正则表达式是/:(.*)/g ,但它也捕获了':_'

I want to achieve--> c 我想实现-> c

What I've got--> :_c 我所拥有的-> :_c

How do I exclude them? 如何排除它们?

PS: replaced space with underscore , for easy understanding. PS:用下划线代替空格 ,以便于理解。

EDIT: I want to capture everything behind ': ' 编辑:我想捕获':'后面的所有内容

EDIT2: here is regexr with text, as u can see, it also captures ': ' EDIT2:这是带有文本的regexr ,如您所见,它还捕获了':'

You can use: /:\\s(.*)/g . 您可以使用:/: /:\\s(.*)/g .*)/ /:\\s(.*)/g

That will capture a single space after a : before starting to capture: 在开始捕获之前,将在:之后捕获一个空格:

a b: c => "c"
a: c   => "c"

 var re = /:\\s(.*)/; var tests = [ 'a: c', 'a: cat', 'ba: test', 'a: c', 'Test: this is the rest of the sentence', ]; for (var i = 0; i < tests.length; i++) { console.log('TEST: ', '"' + tests[i] + '"'); console.log('RESULT: "' + tests[i].match(re)[1] + '"'); } 

Note: You must get the first capture group from the match. 注意:必须从比赛中获得第一个捕获组。 If you do not, you will not get the desired result. 否则,您将无法获得理想的结果。 See How do you access the matched groups in a JavaScript regular expression? 请参阅如何在JavaScript正则表达式中访问匹配的组? for information on how to do this. 有关如何执行此操作的信息。

If you know that underscore will always prefix the c you could do this: /:_?(.*)/g 如果您知道下划线将始终为c前缀,则可以执行以下操作:/: /:_?(.*)/g

The _? _? matches 0 or 1 underscores, so you will only get c as a result. 匹配0或1下划线,因此结果只能是c

 console.log('ab:_c'.match(/:_?(.*)/)[1]) 

Do you want to get the string "c" or the last character? 是否要获取字符串“ c”或最后一个字符?

var a = "a:_c a b:_c";

/c/g.exec(a)

/.$/g.exec(a)

Edit to match comment: 编辑以匹配评论:

Use the following to remove everything before and including ":_" 使用以下命令删除“:_”之前的所有内容,包括“:_”

a.replace(/.*:_*/, '')

For space: 对于空间:

a.replace(/.*:\s*/, '')

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

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