[英]How can I use regex to match both single word strings and hyphenated strings?
I am trying to match the first word after a specific string using regex and have been struggling to make all instances work properly. 我试图匹配使用正则表达式的特定字符串之后的第一个单词,并一直在努力使所有实例正常工作。 Let's say I have 2 strings:
假设我有2个字符串:
Site Code: foobar
Site Code: hello-world
Now, using (?<=\\bSite Code:\\s)(\\w+)
returns foobar
which is correct, but only returns hello
when I need hello-world
instead. 现在,使用
(?<=\\bSite Code:\\s)(\\w+)
返回正确的foobar
,但只在我需要hello-world
时才返回hello
。
So, I changed my expression to (?<=\\bSite Code:\\s)(\\w+)(-\\w+)
in order to pickup the hyphenated words, but now it is ignoring the non-hyphenated words. 因此,我将表达式更改为
(?<=\\bSite Code:\\s)(\\w+)(-\\w+)
以便拾取带连字符的单词,但现在它忽略了非连字符的单词。
Is there a way to get both foobar
and hello-world
from the same expression? 有没有办法从同一个表达式获得
foobar
和hello-world
?
Try this (?<=\\bSite Code:\\s)(\\S+)
试试这个
(?<=\\bSite Code:\\s)(\\S+)
Without more detail on the requirements it's hard to give an exact answer. 如果没有更多关于要求的细节,很难给出确切的答案。 The above regex should match all non-whitespace characters after the specific string "Site Code: ".
上面的正则表达式应该匹配特定字符串“Site Code:”之后的所有非空格字符。
Try this regex: 试试这个正则表达式:
(?<=\bSite Code:\s)([-\w]+)
#\w only include the range [A-Za-z0-9_] in ascii mode.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.