简体   繁体   中英

I need some help for a specific regex in javascript

I try to set a correct regex in my javascript code, but I'm a bit confused with this. My goal is to find any occurence of "rotate" in a string. This should be simple, but in fact I'm lost as my "rotate" can have multiple endings! Here are some examples of what I want to find with the regex:

  • rotate5
  • rotate180
  • rotate-1
  • rotate-270

The "rotate" word can be at the begining of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.

Can someone help me please?

EDIT: What I tried so far (probably missing some of them):

  • /\\wrotate.*/
  • /rotate.\\w*/
  • /rotate.\\d/
  • /\\Srotate*/

I'm not fully understanding the regex mechanic yet.

Try this regex as a start. It will return all occurrences of a "rotate" string where a number (positive or negative) follows the "rotate".

/(rotate)([-]?[0-9]*)/g

Here is sample code

 var aString = ["rotate5","rotate180","rotate-1","some text rotate-270 rotate-1 more text rotate180"]; for (var x = 0; x < 4; x++){ var match; var regex = /(rotate)([-]?[0-9]*)/g; while (match = regex.exec(aString[x])){ console.log(match); } } 

In this example,

match[0] gives the whole match (eg rotate5)

match[1] gives the text "rotate"

match[2] gives the numerical text immediately after the word "rotate"

If there are multiple rotate stings in the string, this will return them all

If you just need to know if the 'word' is in the string so /rotate/ simply will be OK.

But if you want some matching about what coming before or after the @mseifert will be good

If you just want to replace the word rotate by another one you can just use the string method String.replace use it like var str = "i am rotating with rotate-90"; str.repalace('rotate','turning')' var str = "i am rotating with rotate-90"; str.repalace('rotate','turning')'

WHy your regex doesnt work ?

/\wrotate.*/ 

means that the string must start with a caracter [a-zA-Z0-9_] followed by rotate and another optional character

/rotate.\w*/

meanse rotate must be followed by a character and others n optional character ...............

Using your description:

The "rotate" word can be at the beginning of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.

This regex should do the work:

const regex = /(^rotate|rotate$|\ {1}rotate\ {1})/gm;

You can learn more about regular expressions with these sites:

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