J. Doe
J. Doe

Reputation: 1

Regex between a string

Example:

I have the following string

a125A@@THISSTRING@@.test123

I need to find THISSTRING. There are many strings which are nearly the same so I'd like to check if there is a digit or letter before the @@ and also if there is a dot (.) after the @@.

I have tried something like:

([a-zA-Z0-9]+@@?)(.+?)(.@@)

But I am unable to get it working

Upvotes: 0

Views: 66

Answers (3)

Valdi_Bo
Valdi_Bo

Reputation: 30971

You wrote:

check if there is a digit or letter before the @@

I assume you mean a digit / letter before the first @@ and check for a dot after the second @@ (as in your example).

You can use the following regex:

[a-z0-9]+  # Chars before "@@", except the last
(?:        # Last char before "@@"
  (\d)     # either a digit - group 1
  |        # or
  ([a-z])  # a letter - group 2
)
@@?        # 1 or 2 "at" chars
([^@]+)    # "Central" part - group 3
@@?        # 1 or 2 "at" chars
(?:        # Check for a dot
  (\.)     # Captured - group 4
  |        # or nothing captured
)
[a-z0-9]+  # The last part
# Flags:
# i - case insensitive
# x - ignore blanks and comments

How it works:

  • Group 1 or 2 captures the last char before the first @@ (either group 1 captures a digit or group 2 captures a letter).
  • Group 3 catches the "central" part (THISSTRING, a sequence of chars other than @).
  • Group 4 catches a dot, if any.

You can test it at https://regex101.com/r/ATjprp/1

Your regex has such an error that a dot matches any char. If you want to check for a literal dot, you must escape it with a backslash (compare with group 4 in my solution).

Upvotes: 0

Rahul
Rahul

Reputation: 2738

But I am unable to get it working.

Let's deconstruct what your regex ([a-zA-Z0-9]+@@?)(.+?)(.@@) says.

([a-zA-Z0-9]+@@?) match as many [a-zA-Z0-9] followed by a @ followed by optional @.

(.+?) any character as much as possible but fewer times.

(.@@) any character followed by two @. Now . consumes G and then @@. Hence THISSTRING is not completely captured in group.


Lookaround assertions are great but are little expensive.

You can easily search for such patterns by matching wanted and unwanted and capturing wanted stuff in a capturing group.

Regex: (?:[a-zA-Z0-9]@@)([^@]+)(?:@@\.)

Explanation:

(?:[a-zA-Z0-9]@@) Non-capturing group matching @@ preceded by a letter or digit.

([^@]+) Capturing as many characters other than @. Stops before a @ is met.

(?:@@\.) Non-capturing group matching @@. literally.

Regex101 Demo


Javascript Example

var myString = "a125A@@THISSTRING@@.test123";
var myRegexp = /(?:[a-zA-Z0-9]@@)([^@]+)(?:@@\.)/g;
var match = myRegexp.exec(myString);
console.log(match[1]);

Upvotes: 0

Ofir Winegarten
Ofir Winegarten

Reputation: 9355

You can use look behind and look ahead:

(?<=[a-zA-Z0-9]@@).*?(?=@@\.)

https://regex101.com/r/i3RzFJ/2

Upvotes: 2

Related Questions