-2

I need some clever code to show me how to do this. I cannot use substring, split, etc because there is no specific character to search on. I thought about looping the String and reading each character and have numerous if statements to test, but hoping there is a simpler way of doing this.

String str = "'1_First Name'='1_Johns' AND '200_Age' > '30' OR '123_Dog:name' IS 'Bolt'";
Output needed: "'1'='1_Johns' AND '200' > '30' OR '123' IS 'Bolt'"

This is a Remedy Query string. The '1_First Name' is the column name and the '1_Johns' is the column value.

I appended the column names with the column id_ which then gives me for example: '1_First Name'.

In Remedy we can search on column name or column ID. However column names can be the same, but column id's are unique.

So that is why only some parts of the string must be manipulated and others not.

Quentinb
  • 476
  • 1
  • 9
  • 30

1 Answers1

2
str = str.replaceAll("('\\d+)_[^']+'(?=\\s*([<>=!]|IS))", "$1'");
  • ('\\d+)_[^']+' is the match for every variable.
  • with a lookahead (?=\\s*([<>=!]|IS)) for a following operator; lookahead (?= ... ) with pattern \\s*([<>=!]|IS).

This more or less distinguishes between variable and value, both having the same regular pattern.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    @Pshemo for a moment I had that thought: "do not forget the final `'`"; but one gets old. ;) – Joop Eggen Jun 11 '19 at 14:38
  • Awesome and so very close. The output is dropping a single quote. I am getting: '1='1_Johns' instead of '1'='1_Johns' – Quentinb Jun 11 '19 at 14:47
  • I corrected it to `"$1'"`, thanks an already deleted comment from Pshemo. (An extra apostrophe after 1.) – Joop Eggen Jun 11 '19 at 14:48
  • PERFECT, thank you. Clearly you are the regex master. – Quentinb Jun 11 '19 at 14:52
  • 1
    Maybe this would be little easier to read/maintain `.replaceAll("'(?\\d+)_[^']+'(?=\\s*([<>=!]|IS))", "'${colID}'")`. (1) used named-group to better show intent of regex (2) moved `'` out of group and added another `'` at start of replacement - this makes it less *strange* than that single dandling `'` at the end of replacement. – Pshemo Jun 11 '19 at 16:21
  • @Pshemo indeed more readable, more abstract and less prone to a slip of the pen. – Joop Eggen Jun 12 '19 at 07:03