A. D.
A. D.

Reputation: 768

Detect if a string has a quote in it and that quote has a comma inside it

I want to check if strings that have a quote in them (denoted by quotation marks "") contain a comma right before the quote ends.

See these examples:

1)

He said "hi," then left.

2)

He said "hi", then left.

3)

He said "hi, ho", then left.

In 1) there's a comma before the second quotation mark so this should be caught by the regex.

2) shouldn't be caught.

3) shouldn't be caught either.


So I want to get a positive only if the string contains a quote and that quote has a comma inside it right before it ends. I don't need anything except the true or false result from this regex.

I apologize that I don't have a regex to present - I've never worked with this and only need it for a single filter rule for reddit enhancement suite :S

Oh yeah this should be in javascript regex (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)

Upvotes: 1

Views: 474

Answers (4)

Thomas
Thomas

Reputation: 12647

don't know what to explain about this:

let pattern = /"[^"]*,[^"]*"/g;

let strings = [
  'He said "hi," then left.',
  'He said "hi", then left.',
  'He said "hi, ho", then left.',
  '"He" said "hi," then "left."',
];

strings.forEach(str => {
  console.log(str);
  console.log(str.match(pattern));
})
.as-console-wrapper{top:0;max-height:100%!important}

Upvotes: 0

Jan
Jan

Reputation: 43159

Use a positive lookahead like so

"[^"]+,(?=")

Along with .test(), see a demo on regex101.com.

Upvotes: 3

Ognjen Stanojevic
Ognjen Stanojevic

Reputation: 63

String a1 = "He said \"hi,\" then left.";
String a2 = "He said \"hi\", then left.";
String test = ",\"";

if(a2.contains(test)) will give u false and if (a1.contains(test)) will give u true...

Upvotes: 0

dfsq
dfsq

Reputation: 193281

Simple regexp will do the job:

/".*?,"/

Test it: https://regex101.com/r/3cl4h5/1

Upvotes: 3

Related Questions