简体   繁体   中英

Regex to match a word only when the line starts with a certain string

I want to make a Regex to match something only when the line starts with a given string. Given the following two lines, I want to match width and height only in the 1st string:

frame at x1 y1 width 50 height 200 rectangle at x1 y1 width 50 height 200

The closest I got was this:

(?<=frame\\s).*(width|height)

But this expression is matching everything between frame and 200

在此处输入图片说明

I'm using https://rubular.com/ to test it.

You can try this \\Aframe.*width\\s(?<width>\\d+)\\sheight\\s(?<height>\\d+)\\z

In ruby, the result would like在此处输入图片说明

r = /\Aframe\b.*\swidth\s+(\d+)\s+height\s+(\d+)/ 

"frame at x1 y1 width 50 height 200".scan(r).flatten
  #=> ["50", "200"] 
"rectangle at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"framer at x1 y1 width 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 bandwidth 50 height 200".scan(r).flatten
  #=> []
"frame at x1 y1 width 50 midheight 200".scan(r).flatten
  #=> []

Is using match groups an option? In your example, the full match is at x1 y1 width 50 height , but the match group is just width . What do you want to capture, the values for width and height?

If you know the format of the strings (as in, width is always before height ), then you can have a regex like this:

/\Aframe.*width (?<width>\d+).*height (?<height>\d+)/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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