1

Can someone help me modify this Regex pattern so that it doesn't use positive lookahead and lookbehind since these are not compatible with JS and .NET?

The idea is that I am trying to get a first match of any characters that are between "-" and "-" ie. NY from a string like this: DSK-NY-110. Here's what I got that works but it won't work in JS and .NET at the same time so I need something that is compatible with both:

(?<=\-)\w+(?=\-)

Thanks!

10
  • 2
    Use -(\w+)- to grab the Group 1 value. Commented May 9, 2019 at 15:18
  • .NET supports lookarounds Commented May 9, 2019 at 15:18
  • @WiktorStribiżew I don't want to work under the assumption that there will be groups returned. Is there a way to just make it ignore the two bounding characters? Commented May 9, 2019 at 15:19
  • 1
    @Thefourthbird I know .NET does but this regex is shared between JS and .NET so it has to work in both. Commented May 9, 2019 at 15:19
  • Then your problem has no solution unless you only target ECMAScript 2018 compliant JS environments (where lookbehinds are supported, as e.g. in Chrome). I'd rather you do support groups in your solution, they are more flexible. Commented May 9, 2019 at 15:20

1 Answer 1

1

The safest approach is to rely on capturing groups and extract the submatches using appropriate code-behind.

The regex may look like

-(\w+)-
 |---|-> Group 1

and then all you need is to get the Group 1 value:

C#:

var groupID = 1; // It can even be user input
var result = Regex.Match(s, @"-(\w+)-")?.Groups[groupID].Value;

In JS:

var groupID = 1, s = "Some-string-here", m;
var result = (m=s.match(/-(\w+)-/)) ? m[groupID] : "";
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.