开发者

regex in groovy

开发者 https://www.devze.com 2023-01-04 09:30 出处:网络
I need to remove \"\" from the both ends of the line \"/开发者_StackOverflow中文版home/srinath/junk/backup\"

I need to remove "" from the both ends of the line

"/开发者_StackOverflow中文版home/srinath/junk/backup"

and to display like this /home/srinath/junk/backup

How can we achieve this in groovy ?

thanks in advance, sri..


You want to replace ^"|"$ with the empty string. The ^ and $ are the beginning and end of string anchors, respectively. | is the alternation metacharacter.

References

  • regular-expressions.info/Anchors and Alternation

Snippet

These were tested on lotrepls.appspot.com:

Groovy >>> println('"hello" "world"'.replaceAll('^"|"$',''));
hello" "world

Groovy >>> println('bleh'.replaceAll('^"|"$', ''));
bleh

Groovy >>> println(''.replaceAll('^"|"$', ''));
(blank)

As specified, replaceAll('^"|"$','') removes only doublequotes at the beginning and end of the string, if they're there. Internal doublequotes, if there are any, will be left untouched.


You don't have to use a regex. If you always want to remove the first and last characters you can do this with

'"/home/srinath/junk/backup"'[1..-2]

Alternatively, to remove all double quotation marks use

'"/home/srinath/junk/backup"'.replaceAll'"', ''
0

精彩评论

暂无评论...
验证码 换一张
取 消