如何组合正则表达式 + MySQL 中的更新以向名字姓氏添加空格
两部分:
总体问题: 我正在尝试更正数百条记录中的 post_title
条目。它们被导入为“JohnDoe”,而本应是“John Doe”
第 1 部分: 在 MySQL 中,尝试SELECT
所有与小写字母后跟大写字母 [aZ] 匹配的内容:
SELECT `post_title`
FROM wp_posts
WHERE `post_title`
REGEXP '[a-z]\S[A-Z]'
但是,这也会检索“Dr.”的实例。 John Doe',这实际上是一个正确的条目。我仅需要它来检索它,当大写字母直接跟随小写字母时,并且仅当字符串中没有空格
部分第二个: 然后,我尝试通过在名字和姓氏之间添加空格字符来更新这些选定的记录。也不知道如何用 mysql 准确地做到这一点。我确信这是某种疯狂的火星嵌套 SELECT/UPDATE/WHERE/REGEX 语句,但这超出了我的能力范围。
不知道。
谢谢
A TWO-PARTER:
OVERALL ISSUE:
I'm trying to correct a post_title
entry on hundreds of records. They were imported as 'JohnDoe' when they should have been 'John Doe'
PART the 1st:
In MySQL, trying to SELECT
all that match a lowercase followed by Uppercase [aZ] with:
SELECT `post_title`
FROM wp_posts
WHERE `post_title`
REGEXP '[a-z]\S[A-Z]'
However, that also retrieves instances of 'Dr. John Doe', which is actually a correct entry. I need it only to retrieve it when the Uppercase directly follows a lowercase, and only when there are NO spaces in the string whatsoever
PART the 2nd:
I'm trying to then UPDATE those SELECTED records by adding a space character in between the first and last names. Not sure how to do that exactly with mysql, either. I'm sure it's some kind of crazy Martian nesting of SELECT/UPDATE/WHERE/REGEX statements but that's way beyond me.
No idea.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,使用 REGEXP 的模式匹配不区分大小写。所以你必须使用 BINARY。
我不确定 MySQL 中是否有更好的方法来做到这一点,但这是一个。对从 A 到 Z 的每个字母表运行以下查询。我已经给出了 A、B、C、D、E、Y 和 Z 的查询。请复制所有其他字母表。一旦你完成所有的运行,你的名字和姓氏之间就会有一个空格
。请注意上面查询示例中 BINARY 的用法。
另一种方法可能是编写一个 PHP 脚本来读取所有
post_title
,然后使用强大的 PHP 正则表达式函数添加空格并将其更新回数据库。希望这有帮助!
编辑:哦!我忘记了数据库也有带空格的条目,它们需要被忽略。请改用此查询:
First, pattern matching using REGEXP is case-insensitive. So you've to use BINARY.
I'm not sure if there is a better way of doing this in MySQL but this is one. Run the following queries for each of the alphabet from A to Z. I've given the queries for A, B, C, D, E, Y and Z. Please copy for all other alphabets. Once you've completed running them all, you will have a space between the first and last names
Please note the usage of BINARY in the above query examples.
Another way might be to write a PHP script to read all
post_title
and then use powerful PHP regular expression functions to add spaces and update them back to the database.Hope this helps!
EDIT: Oh! I forgot that the database also has entries with spaces and they need to be ignored. Please use this query instead: