简体   繁体   English

正则表达式匹配不同情况下字符之前或之后的内容

[英]Regex to match what's before or after a character in different situations

I have some troubles writing a regex我在编写正则表达式时遇到了一些麻烦

What I want to achieve, I want to match the following string 6.62 X 25.250755 L but only what is after the X character or there may be cases when I have to match the following string 25.250755 X 6.62 in this case I need to match what's before the X character and the final case is when I have something like this: 25.250755 LX 6.62 or 25.250755LX 6.62 (with or without space, with or without the L character)我想要实现的是,我想匹配以下字符串6.62 X 25.250755 L但只匹配X字符之后的内容,或者可能在某些情况下我必须匹配以下字符串25.250755 X 6.62在这种情况下我需要匹配之前的内容X字符和最后一种情况是当我有这样的东西时: 25.250755 LX 6.6225.250755LX 6.62 (有或没有空格,有或没有L字符)

This is what I have so far, but is not enough and I don't know how to continue form here on到目前为止,这是我所拥有的,但还不够,我不知道如何在此继续形成

/[Xx]([\s\S]*)$/gm

([0-9]*[.])?[0-9]+ ?L? X ([0-9]*[.])?[0-9]+ ?L? should work.应该管用。

For your example data, you can repeat a group with a capture group to capture the value of the last iteration.对于您的示例数据,您可以使用捕获组重复一个组以捕获上次迭代的值。

(?: ?\b(\d+(?:\.\d+)) ?[XL])+\b
  • (?: Non capture group (?:非捕获组
    • ?\\b Match an optional space and a word boundary ?\\b匹配一个可选的空格和一个单词边界
    • ( Capture group 1 (捕获组 1
      • \\d+(?:\\.\\d+) Match 1 or more digits with an optional decimal part \\d+(?:\\.\\d+)匹配 1 个或多个带有可选小数部分的数字
    • ) Close group 1 )关闭第 1 组
    • ?[XL] Match an optional space and either X or L ?[XL]匹配一个可选的空格和 X 或 L
  • )+ Close the non capture group and repeat it 1 or more times )+关闭非捕获组并重复 1 次或多次
  • \\b A word boundary \\b一个词边界

Regex demo正则表达式演示

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

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