0

Hi how to create a regular expression which the pattern should only have 1 instance of "

For example:

1. STRING" 
2. "STRING
3. STRI"NG
4. STRING""
5. "STRING"

Result:

1. STRING""
2. ""STRING
3. STRI""NG
4. STRING"" (No change since 2 instance of ")
5. "STRING"   (No change since 2 instance of ")

1 Answer 1

4

Something like this:

with t as (
  select 'STRING"' as s from dual union all
  select '"STRING' from dual union all
  select 'STRI"NG' from dual union all
  select 'STRING""' from dual union all
  select '"STRING"' from dual union all
  select 'STRING' from dual union all
  select '"STR"ING"' from dual union all
  select '"' from dual union all
  select '""' from dual union all
  select '"""' from dual
)
select
  s,
  regexp_replace(s,'^([^"]*)"([^"]*)$', '\1""\2') new_s
from t

Output:

+-----------+-----------+
|     S     |   NEW_S   |
+-----------+-----------+
| STRING"   | STRING""  |
| "STRING   | ""STRING  |
| STRI"NG   | STRI""NG  |
| STRING""  | STRING""  |
| "STRING"  | "STRING"  |
| STRING    | STRING    |
| "STR"ING" | "STR"ING" |
| "         | ""        |
| ""        | ""        |
| """       | """       |
+-----------+-----------+

Explanation:

^       # asserts position at start of a line
(       # 1st capturing group
 [^"]*  # matches characters that are not the character ", zero or more times
)
"       # matches the character " literally
(       # 2nd capturing group
 [^"]*
)
$       # asserts position at the end of a line

Check it online with rextester.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked perfectly! Thanks! Plus points because of the explanation... it really helped.
@Maguzu, thanks for your friendly feedback. I was glad to help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.