0

I get an issue using REGEX, it is probably about my REGEX but I need some helps.

I need to match all string containing "D"...

Test string 1 : D
Test string 2 : aaaaaaDqqqqq
Test string 3 : Dssssssss
Test string 4 : D4564646
Test string 5 : 1321313D2312
Test string 6 : ppppprrrrrr

My regex :

/^.+D.+|(:?^|\s)D$/gi

It works only for 1 and 2 and it should works for 1, 2, 3, 4 and 5.

3
  • 2
    Maybe ^.*D.*$? Or [^D]*D[\s\S]*. Commented Aug 29, 2018 at 13:40
  • Thank you it works with .*. Commented Aug 29, 2018 at 13:44
  • 2
    However, it seems you may just use indexOf or includes, which is a more natural way to check if a char exists in an input string in JavaScript. Commented Aug 29, 2018 at 13:45

4 Answers 4

0

In your case problem is with + operator which is literally Matches between one and unlimited times so it wont work if letter "D" will be in the beggining or the end of string. Try this regex: ^.*D.*$ with asterix, as it is defined as Matches between zero and unlimited times

See example

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

1 Comment

^.*D.*$ is inefficient and will choke on multiline input. Do not use it.
0

Following regex should work for you

.*D.*

1 Comment

.*D.* is inefficient and will choke on multiline input. Do not use it.
0

If all you need to do is test for whether or not a string contains a D character, it's just /D/

var tests = [
"D",
"aaaaaaDqqqqq",
"Dssssssss",
"D4564646",
"1321313D2312",
"ppppprrrrrr"
]

tests.forEach(str => console.log(/D/.test(str)))

Comments

-1

Instead of using a regex simply use the includes function

var string = "aaaaaaDqqqqq",
substring = "D";
if(string.includes(substring)){
    console.log("contain")
}else{
    console.log("don't contain")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.