匹配字符的第一个唯一实例 [英] Match first only instance of a character

查看:43
本文介绍了匹配字符的第一个唯一实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串中字符的第一个实例(例如 sdtmig-3-1-2XPath::replace 并将其替换为 / 以便结果字符串是 sdtmig/3-1-2.除了它会有一个或多个破折号之外,我不能保证有关该模式的任何其他内容.我很难找到一个始终匹配 - 的特定第一个实例的正则表达式模式.

I'm trying to match only the first instance of a character in a string like sdtmig-3-1-2 with XPath::replace and replace it with a / so that the resulting string is sdtmig/3-1-2. I cannot guarantee anything else about the pattern other than that it will have one or more dashes in it. I'm having a ton of difficulty finding a regex pattern that consistently matches only that particular first instance of -.

我觉得我很接近:

(?:.+?)(-)(?:.+)

但这也匹配完整的字符串,所以不好.

But this also matches the full string as well, so it is no good.

除了适用于 https://regex101.com 的普通正则表达式外,请不要提供任何解决方案.正则表达式的味道"应该遵守XPath/XQuery语义(https://www.w3.org/TR/xmlschema-2/#regexs).我无法控制正则表达式搜索中的全局标志.

Please do not offer solutions using anything but plain regular expressions that would work on https://regex101.com. The "flavor" of regex should abide by XPath/XQuery semantics (https://www.w3.org/TR/xmlschema-2/#regexs). I cannot control the global flag on the regexp search.

推荐答案

不引入 g(全局标志),正则表达式最多匹配一次.这相当于普通的 replace'sdtmig-3-1-2'.replace('-', '/') 这样的调用导致 "sdtmig/3-1-2".

Without introducing the g (global flag), the regular expression will match at most a single occurrence. This is equivalent to the plain replace call like 'sdtmig-3-1-2'.replace('-', '/') which results in "sdtmig/3-1-2".

请参阅普通正则表达式用法(确保关闭全局修饰符并使用/// 正则表达式,替换为 /).

Please see a plain regular expression usage (make sure the global modifier is turned off and use /-/ regular expression with a substitution of /).

例如:

console.log('sdtmig-3-1-2'.replace(/-/, '/'));

使用全局标志,它将替换所有出现的:

With the global flag, it would replace all the occurrences:

console.log('sdtmig-3-1-2'.replace(/-/g, '/'));

您还可以在第一次出现之前对任何内容使用惰性前缀匹配,并将匹配的组替换为其原始内容,以便它们环绕被替换的字符.请参阅正则表达式:
(.*?)-(.*) 的替代$1/$2.这应该适用于 XQuery 替换功能.

You can also use lazy prefix match of anything before the first occurrence and replace the matched groups with their original contents so they wrap around the replaced character. Please see the regular expression for this:
(.*?)-(.*) and a substitution of $1/$2. This should work with XQuery replace function.

console.log('sdtmig-3-1-2'.replace(/(.*?)-(.*)/, '$1/$2'));

这篇关于匹配字符的第一个唯一实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆