0

I'm trying to create a REGEX to find the string between \ and > in the following input :

\\RANDOM\APPLE\BOB\GEORGE\MIKE\TOM >>\\TEST\TEST2\TEST3\TEST\TEST\JOHN.

Desired Output:TOM

I've been able to create ([^>]+) to isolate the first section of the string before the first > . I just can't seem to figure out how to expand on this and isolate TOM.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
M. Singh
  • 29
  • 6
  • Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen May 23 '19 at 12:37
  • 2
    Try `[^\\>]+(?=\s>>)`, see https://regex101.com/r/R03825/1 – Wiktor Stribiżew May 23 '19 at 12:40
  • 1
    Regex engines in different languages have different capabilities. Can you add either a tag or edit your question to specify the language you are using. – WJS May 23 '19 at 13:11
  • Thanks @WiktorStribiżew , your solution worked – M. Singh May 23 '19 at 13:22
  • You need to do a web search on `lookahead` and `lookbehind assertions`. They are very useful in situations like this. – WJS May 23 '19 at 13:24

2 Answers2

1

Try

\\([^\\>]+?) >>

Regex Demo

In javascript:

let regex = /\\([^\\>]+?) >>/

// Note \\ is required for literal \ in js
let str = "\\\\RANDOM\\APPLE\\BOB\\GEORGE\\MIKE\\TOM >>\\\\TEST\\TEST2\\TEST3\\TEST\\TEST\\JOHN.";

match = str.match(regex);

console.log(match[1]); //TOM
chatnoir
  • 2,185
  • 1
  • 15
  • 17
1

This should works:

[^\\\s>]+(?=\s*>)

Demo:

It will works even if the desired match has one or more > after it and if has one or more whitespaces before >.

I mean: this regex will match TOM from all this strings:

\\RANDOM\APPLE\BOB\GEORGE\MIKE\TOM  >\\TEST\TEST2\TEST3\TEST\TEST\JOHN.
\\RANDOM\APPLE\BOB\GEORGE\MIKE\TOM  >>\\TEST\TEST2\TEST3\TEST\TEST\JOHN.
\\RANDOM\APPLE\BOB\GEORGE\MIKE\TOM>>\\TEST\TEST2\TEST3\TEST\TEST\JOHN.
Pablo
  • 2,137
  • 1
  • 17
  • 16