Match first only instance of a character [duplicat

2020-05-07 05:19发布

问题:

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 -.

I feel like I came close with:

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

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

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.

回答1:

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 /).

For example:

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, '/'));

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'));