在 JavaScript 中使用正则表达式来匹配两个字符
我试图在 JS 中找出一个在两个字符之间匹配的正则表达式,但可能有两种不同的变体,所以它需要知道这一点。我需要在逗号和 (、OR 逗号和字母后跟句点之间进行匹配。(“T.”)
这是我拥有的数据:
Doe, John (SUP)
Doe, John T. (SUP)
Doe, John Smith (SUP)
Doe, John Smith T. (SUP)
Doe, John-Smith (SUP)
Doe, John-Smith T. (SUP)
我需要仅匹配其中的第一个名字。所以它会是这样的:
John
John
John Smith
John Smith
John-Smith
John-Smith
这是到目前为止我有代码:
var nameLinkAdd = nameLink.match(/\,(.*?)\(/g);
有什么建议吗?
I'm trying to figure out a regular expression in JS that matches between two characters but there can be like two different variations so it needs to know that. I need to match between comma and (, OR comma and letter followed by a period. ("T.")
Here's the data I have:
Doe, John (SUP)
Doe, John T. (SUP)
Doe, John Smith (SUP)
Doe, John Smith T. (SUP)
Doe, John-Smith (SUP)
Doe, John-Smith T. (SUP)
I need to match just the first name from that. So it would be like this:
John
John
John Smith
John Smith
John-Smith
John-Smith
Here's the code I have so far:
var nameLinkAdd = nameLink.match(/\,(.*?)\(/g);
Any suggestions? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您后面不一定有
(SUP)
,这将起作用。即,它可以在(?!.)
上运行,确保您不会捕获任何后跟句点
.
的内容。如果你想避免环视(可能是一个速度问题,尽管对于这么短的字符串我不这么认为),请尝试:
然而,这假设所有名称都有多个字母,并以一个大写字母开头,后跟小写字母(其中看起来很合理,有没有内部带有大写字母的名称或仅由一个字母组成的名称?)
This will work if you don't necessarily have the
(SUP)
after. Ie it would work onThe
(?!.)
makes sure you don't capture anything followed by a peroid.
.If you want to avoid lookarounds (could be a speed issue, although with such short strings I don't think so), try:
However this assumes that all names have more than one letter, and start with one capital followed by lowercase (which seems reasonable, are there any names with internal uppercase letters or names consisting of just one letter?)
我喜欢使用 http://regexpal.com/ 来计算正则表达式。
I like to use http://regexpal.com/ to work out a regular expression.
尝试:
您想要的将在组 1 中。
再次
正常*(特殊正常*)*
;)\w
\s*
Try:
What you want will be in group 1.
normal* (special normal*)*
again ;)\w
\s*