简体   繁体   English

正则表达式将 substring 放在字符串中特殊字符的左侧

[英]Regex to get substring to the left of a special character in a string

I have certain expressions that looks like this我有一些看起来像这样的表达

"sum='29'"

'The total score =" 29"'

"Your name = 'John'"

"Your grade is A"

Now what I want to do is to check if the left side of quote ( ' or " ) contains an = .现在我要做的是检查引号( '" )的左侧是否包含=

So this is what I do所以这就是我所做的

leftTermOfQuote = string.match(/\S+(?' *')/)[0]

But I get null .但我得到null What am I doing wrong?我究竟做错了什么?

To get the left side of a ' or " , you could capture the first part in a group while matching the first ' or "要获取'"的左侧,您可以在匹配第一个'"时捕获组中的第一部分

To not cross the quotes or = boundary, you could use a negated character class [^'"\r\n=] matching any char except the listed.要不跨越引号或=边界,您可以使用否定字符 class [^'"\r\n=]匹配除所列字符之外的任何字符。

^([^'"\r\n=]*=[^'"\r\n=]*)['"]

Explanation解释

  • ^ Start of string ^字符串开头
  • ( Capture group 1 (捕获组 1
    • [^'"\r\n=]* Match any char except the quotes, equals sign or newline [^'"\r\n=]*匹配除引号、等号或换行符之外的任何字符
    • = Match the equals sign =匹配等号
    • [^'"\r\n=]* Same as previous character class [^'"\r\n=]*同上一个字符 class
  • ) Close group )关闭组
  • ['"] Match a ' or " ['"]匹配一个'"

Regex demo正则表达式演示

 [ `sum='29'`, `The total score =" 29"`, `Your name = 'John'`, `Your grade is A` ].forEach(s => { let res = s.match(/^([^'"\r\n=]*=[^'"\r\n=]*)['"]/); if (res) { console.log(res[1]); } })

Now what I want to do is to check if the left side of quote (' or ") contains an =.现在我要做的是检查引号('或“)的左侧是否包含=。

You can do that by searching for =.*['"] . But this would also find The result is 'A=B' because =B' matches the requirements.您可以通过搜索=.*['"]来做到这一点。但这也会找到The result is 'A=B'因为=B'符合要求。

So you can anchor the regex to the first character and request that before the first quote, there is an equal sign:因此,您可以将正则表达式锚定到第一个字符并请求在第一个引号之前有一个等号:

^[^'"]*=[^'"]*['"]

This reads as: "from the beginning of the string ^, there may be non-quotes [^'"], in any number *, before an equal sign =, followed by any number of non-quotes, finally followed by a quote"这读作:“从字符串 ^ 的开头,可能有非引号 [^'”],在任意数量的 * 中,在等号 = 之前,后跟任意数量的非引号,最后是引号"

You can also parse the whole assignment:您还可以解析整个作业:

^([^=]*)\\s*=\\s*"\\s*(.*)\\s*"

this will also extract the parenthesized parts of the assignment, giving you an array with whatever is on the left of the equal sign, and whatever is on the right inside the quotes.这还将提取赋值的括号部分,为您提供一个数组,其中包含等号左侧的任何内容,以及引号内的任何内容。 It should also remove whitespaces, so它还应该删除空格,所以

'  The total score     =   "  29"  '

is parsed into被解析成

[ "The total score", "29" ]

You can use the split and includes functions as well:您也可以使用split包含函数:

const word = 'The total score =" 29"';
const wordSplitByQuotes = word.split(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/);
const containsEqualSign = wordSplitByQuotes[0].includes('=');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM