-1

Given is a string variable elementOne.

def elemenOne = 'AB_CD_EF_GH'

The challenge is to extract only the 'AB', the first part of its value, only that which precedes the first underscore symbol (counted from the left to right).

I have written a code:

def elementTwo = (element_one =~ /^.*(?=(_))/)[0][0]

but it extracts 'AB_CD_EF' instead of only 'AB'.

How should I modify my code, in order to extract only 'AB' part from 'AB_CD_EF_GH'?

Thank you!

MaratC
  • 6,418
  • 2
  • 20
  • 27
youtube2019
  • 165
  • 9

2 Answers2

0

You don't need to use a regexp for this... Which can end up with code that's easier to read later on...

Here's some techniques... The last one is a regexp method

def elemenOne = 'AB_CD_EF_GH'

assert 'AB' == elemenOne.takeWhile { it != '_' }
assert 'AB' == elemenOne.split('_').head()
assert 'AB' == (elemenOne =~ '([^_]+)_.*')[0][1]
tim_yates
  • 167,322
  • 27
  • 342
  • 338
0

There are details missing that might affect your decision about how best to do this but for a starting point, this will evaluate to the result you are looking for...

def inputString = 'AB_CD_EF_GH'

def match = (inputString =~ /^[^_]+(?=_)/)[0]

println match
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47