简体   繁体   English

REGEX:匹配字符串的开头OPTIONALLY

[英]REGEX: Match at the beginning of a string OPTIONALLY

Im building a regex to match the word combo W7 . 我正在建立一个正则表达式来匹配单词combo W7 Not W73 or NW7 or 2W7 . 不是W73NW72W7

So far I have 到目前为止,我有

^w7{1}\b

which works perfectly. 完美地运作。 However, I have a problem. 但是,我有一个问题。

I also need to have //W7 (with 2 forward slashs) also match. 我还需要//W7 (带有2个正斜杠)也要匹配。 So if W7 or //W7 are entered they should match 因此,如果输入W7//W7则它们应该匹配

Any ideas? 有任何想法吗?

Thanks! 谢谢!

Just add an optional // at the start. 只需在开头添加一个可选的//

^(//)?w7\b

You may need to escape them. 您可能需要逃脱它们。

^(\/\/)?w7\b

You could just add an optional group to your regex 您可以将一个可选 添加到正则表达式中

^(?://)?W7\b

Remember to use a non- / delimiter (it's tidier than escaping those slashes). 记住要使用非/ 定界符 (比转义那些斜杠更整洁)。

If you want the subject string to only ever contain //W7 or W7 then an alternative (full pattern) would be: 如果您希望主题字符串仅包含//W7W7则替代方法(完整模式)将是:

~^(?://)?W7$~D

What about ^(//)?W7 ? ^(//)?W7呢? the question mark indicates one or zero occurrences . 问号表示发生一次或零次

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

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