البحث عن سلاسل الاقتباس
قم بإنشاء regexp للعثور على سلاسل في علامات اقتباس مزدوجة الموضوع:" ... "
.
يجب أن تدعم السلاسل الهروب ، بنفس الطريقة التي تدعمها سلاسل JavaScript. على سبيل المثال ، يمكن إدراج علامات الاقتباس كـ \"
سطر جديد مثل \ n
، والشرطة نفسها كـ \\
.
let
str =
"Just like \"here\"."
;
يرجى ملاحظة ، على وجه الخصوص ، أن الاقتباس الهارب موضوع: \"
لا ينهي سلسلة.
لذلك يجب علينا البحث من اقتباس واحد إلى الآخر تجاهل علامات الاقتباس الهاربة على الطريق.
هذا هو الجزء الأساسي من المهمة ، وإلا سيكون تافها.
أمثلة على السلاسل المراد مطابقتها:
.
.
"test me"
.
.
.
.
"Say \"Hello\"!"
...
(
escaped quotes inside)
.
.
"\\"
.
.
(
double slash inside)
.
.
"\\ \""
.
.
(
double slash and an escaped quote inside)
في جافا سكريبت ، نحتاج إلى مضاعفة الخطوط المائلة لتمريرها مباشرة في السلسلة ، مثل هذا:
let
str =
' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. '
;
// the in-memory string
alert
(
str)
;
// .. "test me" .. "Say \"Hello\"!" .. "\\ \"" ..
الحل: /" (\\. | [^ "\\]) *" / g
.
خطوة بخطوة:
- First we look for an opening quote
"
- Then if we have a backslash
\\
(we have to double it in the pattern because it is a special character), then any character is fine after it (a dot). - Otherwise we take any character except a quote (that would mean the end of the string) and a backslash (to prevent lonely backslashes, the backslash is only used with some other symbol after it):
[^"\\]
- …And so on till the closing quote.
بشكل:
let
regexp =
/
"(\\.|[^"\\])*"
/
g
;
let
str =
' .. "test me" .. "Say \\"Hello\\"!" .. "\\\\ \\"" .. '
;
alert
(
str.
match
(
regexp)
)
;
// "test me","Say \"Hello\"!","\\ \""