简体   繁体   English

正则表达式:以“%”开头的单词

[英]Regex: Searching for words with '%' at the beginning

I've been trying to figure this out myself but I'm afraid Regular Expressions just aren't my thing. 我一直试图自己解决这个问题,但是我担心正则表达式不是我的事。 In this sample string: "My name is %name and I live in $address." 在此示例字符串中: “我的名字是%name,我住在$ address。” I'm trying to get the words which begin with "%" then replace them with their values in $name or $address depending on what word was found in the regex. 我试图获取以“%”开头的单词,然后将它们替换为$name$address的值,具体取决于在正则表达式中找到的单词。 The new string is then returned complete with the replaced values. 然后,将返回新字符串,其中包含替换后的值。

Should not return words like: aaa%aaa (% isn't the first character) and \\%word (the % is escaped) 不应返回以下单词: aaa%aaa (%不是第一个字符)和\\%word (%被转义)

This is in PHP. 这是在PHP中。 I'm using this since I'm grabbing the data from a *.ini file where everything is a string. 我正在使用它,因为我是从* .ini文件中抓取数据的,其中所有内容都是字符串。 I remove the $_POST example so it's not misleading. 我删除了$ _POST示例,以免引起误解。

This one should do fine: 这应该做得很好:

(?<!\\|\w)%\w+

However it's usually a bad thing to not sanitize $_POST/$_GET before display/whatever. 但是,在显示之前/任何之前不对$ _POST / $ _ GET进行消毒通常是一件坏事。

In javascript or similar REGEX engines you could use: 在javascript或类似的REGEX引擎中,您可以使用:

\B(%\w+)\b

Edit: 编辑:
In this case, the final \\b is optional, since \\w will match all chars needed and stop in any non word char as @tchrist pointed out. 在这种情况下,最后的\\b是可选的,因为\\w将匹配所需的所有字符,并停止使用@tchrist指出的任何非单词char。

Edit 2: This will not match \\%name : 编辑2:这将不匹配\\%name

(?:^|\s)(%\w+)

This looks like it possibly works. 这看起来可能可行。 This align's on even escapes. 这种对齐方式甚至可以逃脱。 - --

(?<!\\\\)(?:\\\\.)*(?<![%\\w])%(\\w+)

expanded - 展开-

(?<!\\)     # Not an escape behind us
(?:\\.)*    # 0 or many esc plus anything
(?<![%\w])  # not % nor \w behind us
%(\w+)      # % then capture grp1 bunch of word chars

Something like this would be helpful. 这样的事情会有所帮助。

$string = "Hello %name from %city ";

$name = "Joe";
$city = "Boston";
$array = array();


preg_match("/%\w+/",$string,$array);

foreach($array as $string1)
               echo "match: ".$string1;

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

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