在 JavaScript 中使用正则表达式来匹配两个字符

发布于 2024-12-21 23:34:48 字数 491 浏览 0 评论 0原文

我试图在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

落在眉间の轻吻 2024-12-28 23:34:48

如果您后面不一定有 (SUP),这将起作用。即,它可以在 (?!.) 上运行

Doe, John
Doe, John-Smith

nameLink.match(/\, *([A-Za-z]+(?:[- ]+[A-Za-z]+\b(?!\.))*)/)'

,确保您不会捕获任何后跟句点 . 的内容。

如果你想避免环视(可能是一个速度问题,尽管对于这么短的字符串我不这么认为),请尝试:

nameLink.match(/\, *([A-Z][a-z]+(?:[- ]+[A-Z][a-z]+)*)/)'

然而,这假设所有名称都有多个字母,并以一个大写字母开头,后跟小写字母(其中看起来很合理,有没有内部带有大写字母的名称或仅由一个字母组成的名称?)

This will work if you don't necessarily have the (SUP) after. Ie it would work on

Doe, John
Doe, John-Smith

nameLink.match(/\, *([A-Za-z]+(?:[- ]+[A-Za-z]+\b(?!\.))*)/)'

The (?!.) 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:

nameLink.match(/\, *([A-Z][a-z]+(?:[- ]+[A-Z][a-z]+)*)/)'

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?)

梦冥 2024-12-28 23:34:48

我喜欢使用 http://regexpal.com/ 来计算正则表达式。

I like to use http://regexpal.com/ to work out a regular expression.

心如荒岛 2024-12-28 23:34:48

尝试:

nameLink.match(/^(\w+(?:\s*\w+)*)\s+(?:\w\. )?\()/);

您想要的将在组 1 中。

再次正常*(特殊正常*)*;)

  • 正常 = \w
  • 特殊 = \s*

Try:

nameLink.match(/^(\w+(?:\s*\w+)*)\s+(?:\w\. )?\()/);

What you want will be in group 1.

normal* (special normal*)* again ;)

  • normal = \w
  • special = \s*
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文