Select a character if some character from a list is before the character

◇◆丶佛笑我妖孽 提交于 2021-02-17 05:43:52

问题


I have this regular expression:

/([a-záäéěíýóôöúüůĺľŕřčšťžňď])-$\s*/gmi

This regex selects č- from my text:

sme! a Želiezovce 2015: Spoloíč-
ne pre Európu. Oslávili aj 940.

But I want to select only - (without č) (if some character from the list [a-záäéěíýóôöúüůĺľŕřčšťžňď] is before the -).


回答1:


In other languages you would use a lookbehind

/(?<=[a-záäéěíýóôöúüůĺľŕřčšťžňď])-$\s*/gmi

This matches -$\s* only if it's preceded by one of the characters in the list.

However, Javascript doesn't have lookbehind, so the workaround is to use a capturing group for the part of the regular expression after it.

var match = /[a-záäéěíýóôöúüůĺľŕřčšťžňď](-$\s*)/gmi.match(string);

When you use this, match[1] will contain the part of the string beginning with the hyphen.




回答2:


First, in regex everything you put in parenthesis will be broken down in the matching process, so that the matches array will contain the full matching string at it's 0 position, followed by all of the regex's parenthesis from left to right.

/[a-záäéěíýóôöúüůĺľŕřčšťžňď](-)$\s*/gmi

Would have returned the following matches for you string: ["č-", "-"] so you can extract the specific data you need from your match.

Also, the $ character indicates in regex the end of the line and you are using the multiline flag, so technically this part \s* is just being ignored as nothing can appear in a line after the end of it.

The correct regex should be /[a-záäéěíýóôöúüůĺľŕřčšťžňď](-)$/gmi



来源:https://stackoverflow.com/questions/34937226/select-a-character-if-some-character-from-a-list-is-before-the-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!