Uvais Ibrahim
Uvais Ibrahim

Reputation: 741

Seeking help on Regular expression

How can I extract this string from the text using regex

text: {abcdefgh="test-name-test-name-w2-a"} 54554654654 .654654654

Expected output: test-name-test-name-w2

Note: I tried this "([^\s]*)" and the output is test-name-test-name-w2-a. But need the output as I mentioned just above.

Upvotes: 1

Views: 313

Answers (2)

The fourth bird
The fourth bird

Reputation: 163477

You could extend the negated character class to also exclude - and ". Then use a repeating pattern using the same character class preceded with a -

The value is in the first capturing group.

"([^\s-"]+(?:-[^\s-"]+)*)-[^\s-"]+"
  • " Match a " char
  • ( Capture group 1
    • [^\s-"]+ Match 1+ times any char except - " or a whitespace char
    • (?: Non capturing group
      • [^\s-"]+Match 1+ times any char except - " or a whitespace char
    • )* Close non capturing group, repeat 0+ times
  • ) Close capture group
  • -[^\s-"]+ Match 1+ times any char except - " or a whitespace char
  • " Match a " char

Regex101 demo

(On regex101 at the FLAVOR panel you can switch between PCRE and Golang)

Update

To match where the word test is present and not for example test1 you could use a negative lookahead (?![^"\s]*\btest\w) to assert no presence of test followed by a word character.

""(?![^"\s]*\btest\w)([^\s-"]+(?:-[^\s-"]+)*)-[^\s-"]+""

Regex demo

Upvotes: 0

Yves Kipondo
Yves Kipondo

Reputation: 5613

You can try with this regex

.*\"(.*)-.*\".*

The link to regex101 is test

Upvotes: 1

Related Questions